Arithmetic operators · 2 / 18 Theory

Reading numbers from the user

Almost every exercise in this lesson starts by asking the user for one or more numbers. There is an important detail that causes a lot of confusion at first: input() always returns text, even if you type a number.

The problem: input() returns text

x = input("Number: ")
print(x + x)   # if you type 4, it shows 44

Python does not add 4 + 4: it joins two texts, "4" and "4", and gets "44". To do calculations you have to convert the text into a number.

Converting with int() and float()

  • int(text) converts to a whole number: int("8") is 8.
  • float(text) converts to a decimal number: float("3.5") is 3.5.
x = int(input("Number: "))
print(x + x)   # if you type 4, it shows 8

int or float?

Use int when the statement talks about whole numbers and float when there may be decimals. Remember that decimals are written with a dot, not a comma: 3.5, not 3,5.

Careful: int("3.5") raises an error, because "3.5" is not a whole number. If you do not know which number the user will type, float is the safest option.

Asking for several numbers

Each call to input() reads one line. In the exercises you type the values in the input box, one per line, and the program reads them in order:

a = float(input())
b = float(input())
print(a + b)

Converting is useful for other things too

print(float(3))    # 3.0
print(int(3.9))    # 3  (the decimal part is cut off, not rounded)
print(int(-3.9))   # -3

You will see it as soon as you start: almost every exercise uses int(input()) or float(input()).