Exerpad
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!

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:

  1. Read input from the user
  2. Convert to the right type
  3. Compute something
  4. Print the result