Learn Python · lesson 7 of 60 · about 7 minutes
Reading Input
Let your assistant greet whoever runs it: ask questions with input() and turn the answers into the type you need.
What you'll learn
- Read text with input()
- Convert text to numbers with int() and float()
- Convert numbers to text with str()
The assistant only knows Sam
Your assistant greets Sam because Sam is written in the code. Anyone else who runs it is still called Sam. input() fixes that: it shows a question, waits for the person to type an answer and press Enter, and gives you what they typed.
In these examples, the answers typed in aren't shown, only what the program prints.
Asking a question
name = input("Your name? ")
print(f"Good morning, {name}!")Output
Your name? Good morning, Ada!Input is always text
Even if someone types 45, input() gives you the string "45". To do sums with it, convert it:
int("45")gives the whole number 45float("2.5")gives the decimal 2.5str(45)goes the other way, number to text
Convert before you calculate
saved = int(input("Saved so far? "))
print(f"Still to go: {120 - saved}")Output
Saved so far? Still to go: 75What goes wrong without converting
first = "4"
second = "5"
print(first + second)
print(int(first) + int(second))Output
45
9Tidy answers straight away
People type answers with stray spaces and odd capitals, so tidy them as they come in. Methods can follow each other: input("Your name? ").strip().title() asks, trims the spaces, then capitalises.
Tip
int() only reads whole numbers: int("2.5") is a ValueError. Use float() when the answer can have decimals.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.