trylineTryline homeF1 · First steps
About 5 minutes

Asking the user: input()

So far our programs only talked. Now they'll listen: ask the user a question, and turn their answer into a number.

1. Asking a question

input is how a program asks the user something. It shows a question on the screen, waits for the user to type an answer and press Enter, and then hands that answer to your program.

name = input("Your name: ")
print("Hello", name)
OUTPUT
Your name: Alex
Hello Alex
input( )Shows a question, waits, and gives back what the user typed.
"Your name: "The question, inside the round brackets, in quotes.
name =Whatever they type, say Alex, becomes the value, and name is stuck on it.
TRY IT: CHANGE THE QUESTION, THEN RUN

When it asks, the user types: Alex

OUTPUT
Press Run

2. input always gives text

Here's the part that surprises everyone. input always gives back text. Even if you type 26, Python says class str. Because input doesn't know you meant a number. It just hands over the letters you typed.

age = input("Your age: ")
print(type(age))
OUTPUT
Your age: 26
<class 'str'>
The user types 26 into input(). What kind is the value?

3. Turning text into numbers

Python has a tool for that called int. int takes text like 26 and turns it into a real whole number. You wrap it around input.

age = int(input("Your age: "))
print(type(age))
OUTPUT
Your age: 26
<class 'int'>
int( )Turns text into a whole number.
))Two round brackets opened, so two must close: one for input, one for int.

float does the same, but for decimal numbers like a price.

price = float(input("Price: "))
print(type(price))
OUTPUT
Price: 49.5
<class 'float'>

And it works the other way too: str turns a number into text.

4. Two mistakes to watch

A decimal number into int
age = int(input("Your age: "))
ValueError: invalid literal for int() with base 10: '26.5'
int can't turn 26.5 into a whole number. If decimal numbers are possible, use float.
A word into a number
age = int(input("Your age: "))
ValueError: invalid literal for int() with base 10: 'twenty'
Neither int nor float can turn a word into a number, so you get the same ValueError. Later, you'll learn to handle that kindly.
The user may type a price like 49.5. Which is right?

5. Where it's used

Anywhere a program needs something from you: an ATM asking the amount, a form asking your age, a chatbot waiting for your message.

Banking: the ATM amountAgents: a chatbot waiting for your messageForms
Ready for your missionKettle & Crumb: "The bill machine charged Rs 22222222222222222222!"
Start the mission
Was this page clear?