Input
Let the user type something in.
Asking for text
Ask for a name
input() always hands back text, even if they type a number.
name = input("Enter a name: ")
print(f"Hi, {name}!")Sample run
Enter a name: Becca Hi, Becca!
Use their answer in the next question
An f-string works inside input() too.
name = input("Enter a name: ")
age = int(input(f"Hi {name}, how old are you? "))
print(f"{name}, next year you will be {age + 1}.")Sample run
Enter a name: Steve Hi Steve, how old are you? 33 Steve, next year you will be 34.
Asking for a number
Wrap input() in int() for whole numbers or float() for decimals.
Whole number
int() turns the text into a number you can do math with.
age = int(input("Enter an age: "))
print(f"Next year you are {age + 1}.")Sample run
Enter an age: 24 Next year you are 25.
The same thing on two lines
Do it in one step or two. Both work.
age = input("Enter an age: ")
age = int(age)
print(f"Next year you are {age + 1}.")Sample run
Enter an age: 24 Next year you are 25.
Decimal number
Use float() when the answer might have a decimal.
angle = float(input("Enter an angle: "))
print(angle * 2)Sample run
Enter an angle: 31.8 63.6
Watch out
input() always gives a string
They typed a number, but type() shows it is a string (str) until you use int() or float().
age = input("Enter an age: ")
print(type(age))Sample run
Enter an age: 33 <class 'str'>
Forgetting int()
Without int(), age holds the text "24", and text plus a number crashes.
age = input("Enter an age: ")
print(age + 1)What happens
Enter an age: 24 TypeError: can only concatenate str (not "int") to str