Exerpad

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)

If the user types Alex, the output is:

text
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)

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'>

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)

Or do it in one line:

python
age = int(input("How old are you? "))

Converting to Strings

Use str() to convert a number to a string:

python
score = 100
message = "Your score: " + str(score)
print(message)

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