Lesson · Chapter: Input & Type Conversion+10 XP for reading
Talking to the User
So far, our programs always do the same thing. Let's make them interactive!
Prefer to watch? This chapter as a video:
Where you'll use this
Quizzes, chatbots, calculators, login forms — every interactive program starts with reading what the user typed.
Reading Input
The input() function waits for the user to type something:
python
name = input()
print("Hello,", name)
Output
Press Run to see the output.
If the user types Alex, the output is:
Hello, Alex
Input with a Prompt
You can show a message to tell the user what to type:
python
name = input("What is your name? ")
print("Hello,", name)
Output
Press Run to see the output.
Everything is a String
input() always gives you a string, even if the user types a number:
python
age = input("How old are you? ")
print(type(age)) # <class 'str'>
Output
Press Run to see the output.
Converting to Numbers
Use int() to convert a string to a whole number:
python
age_text = input("How old are you? ")
age = int(age_text)
next_year = age + 1
print("Next year you will be", next_year)
Output
Press Run to see the output.
Or do it in one line:
python
age = int(input("How old are you? "))
Output
Press Run to see the output.
Converting to Strings
Use str() to convert a number to a string:
python
score = 100
message = "Your score: " + str(score)
print(message)
Output
Press Run to see the output.
Common Pattern
Most programs follow this pattern:
- Read input from the user
- Convert to the right type
- Compute something
- Print the result
Did you know?
The first computer "bug" was a real insect: in 1947, Grace Hopper's team found a moth stuck inside their computer and taped it into the logbook — "first actual case of bug being found."
Check yourself
Pause & predict — what will this print?
x = input() # the user types: 5 print(x + x)