Convert Input to Numbers with int() and float()
Whole Numbers: int(input())
To get a whole number from the user, wrap input() in int():
age = int(input())
print("Next year you will be", age + 1)Next year you will be 26
This works in two steps, from the inside out:
input()reads the text"25".int()turns it into the number25.
Now age + 1 is real maths: 26.
Think of it as an assembly line: the user's text goes into input(), comes out as a string, goes straight into int(), and comes out as a number.
Adding two numbers, properly this time
a = int(input())
b = int(input())
print(a + b)5
Compare this with the last topic, where the same numbers gave 23. The only difference is int().
Two lines or one?
You can also convert in a separate step. Both versions do the same thing:
| One line | Two lines |
|---|---|
age = int(input()) | text = input() then age = int(text) |
The one-line version is shorter, and it's what most Python programmers write.
Common beginner doubt: "Do spaces around the number matter?" No: int() ignores spaces at the start and end, so " 25 " still becomes 25.
int(input()) reads what the user types and turns it into a whole number.