Everything the user types is collected by input as a string, which is the
data type Python uses for text. That is true even when what they typed looks
like a number. Computers cannot do maths with text, so before you can calculate
with an answer the user typed, you have to convert it into a number.
Converting a piece of data from one type into another is called casting.
Here is what goes wrong without casting. The user types 12, and the program
tries to add 1 to it:
print("How old are you?")
age = input()
print(age + 1)
How old are you?
12
TypeError: can only concatenate str (not "int") to str
Python is telling you that age holds a string, and that a string and a number
cannot be added together. The + on that line means “join two pieces of text”,
because that is what + does to a string, and there is no sensible way to join
the number 1 onto the end of a piece of text.
Worse than an error is a program that runs and gives a nonsense answer. If both sides are strings, Python happily joins them:
print("How old are you?")
age = input()
print(age + age)
How old are you?
12
1212
That is not 24. It is the text 12 written down twice.
int() converts a piece of data into a whole number, and float() converts it
into a decimal number. Wrap the input in whichever one you need, and the
variable holds a number from the very start:
print("How old are you?")
age = int(input())
print(age + 1)
How old are you?
12
13
Read that line from the inside out: input collects the text, int converts
that text into a whole number, and = assigns the number to age. The two
closing brackets at the end are both needed, one for input and one for int.
Use float() whenever the number can have a decimal point in it, such as a
price or a measurement. Here the user types 23.50:
print("What did it cost?")
price = float(input())
print(price * 2)
What did it cost?
23.50
47.0
int() cannot cast text that contains a decimal point. If the user types 12.5
and your code says int(input()), the program stops with
ValueError: invalid literal for int() with base 10: '12.5'. Whole numbers get
int(), anything that may have decimals gets float().
Casting works in the other direction too. To join a number onto a string with
+, you first need a string version of that number, and str() makes one:
num1 = 12
print("You picked number " + str(num1))
You picked number 12
str(num1) does not change what is stored in num1. It produces a string copy
for use on that one line, and the variable itself still holds the number.
Run the code below and type a number when it asks. Then remove the int() from
the second line and run it again, to see the error that casting was preventing.
print("Enter a number and I will double it.")
num1 = int(input())
result = num1 * 2
print("Twice " + str(num1) + " is " + str(result))