Foundations · about 35 min

Reading input: your first interactive program

Why this matters

A program that prints the same thing every time is a fancy text file. Programs become useful when they react to input: a name, a number, a file, a request. This lesson gives you the simplest input channel, reading lines that a user types (or that another program sends through a pipe), and introduces variables to hold what you read. By the end you will write programs that compute answers from data they did not know in advance.

Variables, briefly

To work with a value later, you give it a name:

width = 3
height = 4
area = width * height
print(area)
12

width = 3 is an assignment: evaluate the right-hand side, then make the name on the left refer to the result. = here does not mean "is equal to" in the math sense; read it as "let width refer to 3". The next module explains precisely what a name is in Python (a label attached to an object) and why that matters. For now, a variable is a name for a value.

Names may contain letters, digits and underscores, cannot start with a digit, and are case-sensitive (total and Total are different). By convention Python uses lowercase_with_underscores.

input()

The built-in function input() reads one line from standard input and returns it as a string, with the trailing newline removed:

name = input()
print("Hello,", name)
$ python3 greet.py
Ada
Hello, Ada

When the program reaches input(), it pauses until a line arrives. In a terminal that means until you type something and press Enter.

You can pass a prompt that is printed (without a newline) before waiting:

name = input("What is your name? ")

This is friendly for humans, but the prompt text goes to stdout, so it becomes part of the output. In learnprog exercises, call input() without a prompt unless told otherwise, so your output matches exactly.

What is really happening: stdin

Remember the three standard streams from the last lesson. input() reads from stdin (file descriptor 0). In a terminal, stdin is connected to your keyboard, line-buffered by the terminal driver, which is why nothing is delivered until you press Enter. But stdin can just as well be a file or another program:

$ echo "Grace" | python3 greet.py
Hello, Grace
$ python3 greet.py < name.txt
Hello, Ada

The program does not know or care where the line came from. This is how learnprog tests your code: it runs your program with the test input fed into stdin and captures stdout. It is also how real Unix tools are combined into pipelines.

Strings versus numbers

input() always returns a string, even if the user types digits. Watch what happens:

a = input()   # user types 3
b = input()   # user types 4
print(a + b)
34

For strings, + means concatenation (joining), so "3" + "4" is "34". To do arithmetic, convert the strings to numbers with int() (whole numbers) or float() (numbers with a fractional part):

a = int(input())
b = int(input())
print(a + b)
7

Read int(input()) from the inside out: input() runs first and returns, say, "3"; then int("3") turns it into the integer 3. int() tolerates surrounding whitespace and a leading sign: int(" -42 ") is -42.

Going the other way, str() converts a number to text, which you need when joining with +:

age = 36
print("Age: " + str(age))
print("Age:", age)          # print converts for you

Both print Age: 36. Mixing types with + without converting fails, as you will see below.

A complete small program

Convert a temperature from Celsius to Fahrenheit:

celsius = float(input())
fahrenheit = celsius * 9 / 5 + 32
print(celsius, "C is", fahrenheit, "F")
$ echo 100 | python3 temp.py
100.0 C is 212.0 F

Input, processing, output, in three lines. Notice float prints with .0; formatting numbers nicely is covered in the strings module.

Two more arithmetic operators are handy right away:

Together they split a quantity into units, for example minutes into hours and minutes, as in the last exercise.

Common mistakes

Doing math on strings.

n = input()
print(n + 1)
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(n + 1)
          ~~^~~
TypeError: can only concatenate str (not "int") to str

Python refuses to guess whether you meant "5" + "1" or 5 + 1. Convert explicitly.

Converting text that is not a number.

n = int(input())   # user types: twelve
ValueError: invalid literal for int() with base 10: 'twelve'

int("3.5") fails the same way: int of a string accepts whole numbers only. Use float("3.5") for decimals. Later, in the exceptions lesson, you will catch this error and ask again instead of crashing.

Reading more lines than exist. If stdin runs out (the input had one line, but you called input() twice), you get:

EOFError: EOF when reading a line

EOF means "end of file": stdin is closed and there is nothing more to read. Check how many lines the input really has.

Using a prompt in exercises. input("Enter a number: ") adds Enter a number: to stdout and the output will not match.

Recap

Going further: run a program that uses input() in a terminal and press Ctrl-D instead of typing a line, to see EOFError yourself. Then try printf '3\n4\n' | python3 main.py to feed several lines at once.

Exercises

Exercise 1 · write code

Greeter

Read one line containing a name and print a greeting. For input Ada, the output must be exactly:

Hello, Ada!

Call input() with no prompt text, so that only the greeting is printed.

File: main.py

Starting point

name = input()

Example

input

Ada

expected output

Hello, Ada!

Example

input

Grace Hopper

expected output

Hello, Grace Hopper!
Hint 1

input() returns the line as a string, without its newline.

Hint 2

Join strings with +: "Hello, " + name + "!". Watch the space after the comma and the lack of space before !.

Reference solution
name = input()
print("Hello, " + name + "!")

Exercise 2 · quiz

What type does input return?

The user types 5 and presses Enter. What does this print?

n = input()
print(n * 3)
Answer
  • 555

input() always returns a string, here "5". Multiplying a string by an integer repeats it, so "5" * 3 is "555". To do arithmetic you must convert first: int(input()) * 3 gives 15.

Exercise 3 · write code

Add two numbers

Read two lines, each containing a whole number (possibly negative), and print their sum and product on separate lines, labeled exactly like this. For inputs 3 and 4:

sum: 7
product: 12

File: main.py

Starting point

a = input()
b = input()
print("sum:", a + b)

Example

input

3
4

expected output

sum: 7
product: 12

Example

input

-5
6

expected output

sum: 1
product: -30
Hint 1

a + b on two strings joins them: "3" + "4" is "34".

Hint 2

Wrap each input() in int(...) to get numbers.

Hint 3

print("sum:", a + b) puts one space between the label and the number.

Reference solution
a = int(input())
b = int(input())
print("sum:", a + b)
print("product:", a * b)

Exercise 4 · write code

Minutes to hours

Read a whole number of minutes (zero or more) and print it as hours and minutes. For input 135 the output must be exactly:

135 minutes is 2 hours and 15 minutes

Always use the plural words hours and minutes, even for 1 or 0. Two operators help: // divides and rounds down to a whole number (135 // 60 is 2), and % gives the remainder (135 % 60 is 15).

File: main.py

Starting point

total = int(input())

Example

input

135

expected output

135 minutes is 2 hours and 15 minutes

Example

input

59

expected output

59 minutes is 0 hours and 59 minutes
Hint 1

Store total // 60 and total % 60 in two variables.

Hint 2

print with several comma-separated arguments puts single spaces between them.

Reference solution
total = int(input())
hours = total // 60
minutes = total % 60
print(total, "minutes is", hours, "hours and", minutes, "minutes")