Skip to content
wannacode

Input and output

Problem

The program knows only one name

The program greets the customer by name:

name = "Maria"
print("Hello, " + name + "!")
Output
Hello, Maria!

It works, but it greets everyone as Maria. The name is written in the code. For every new customer you have to change the program and run it again. You want the program to ask on its own.

The idea

Reading from the keyboard

When the program reads, it stops and waits. The person types and presses Enter. What they type is the program's input.

greet.py
name = input("What is your name? ")
print("Hello, " + name + "!")
Input
Maria
Output
What is your name? Hello, Maria!

input("What is your name? ") prints the question in the parentheses, waits for the person to type a line and press Enter, and returns what they typed. Here it is stored in name.

The input and the output are shown separately here. In the console the name appears where you type it: after "What is your name? ". input prints the question without moving to a new line: the answer is on the same line.

More precisely, if you are curious
  • input() with nothing in the parentheses only reads, with no question.
  • If the input has ended (there are no more lines), input() stops the program with EOFError.

Problem

12 + 30 = 1230

The cashier enters two payments, €12 and €30. The program has to show the total:

first = input()
second = input()
total = first + second
print("Total: €" + total)
Input
12
30
Output
Total: €1230

Instead of 42 you got 1230. The program did not get the math wrong. It did no math at all.

There is no question here: input() only reads a line.

The idea

From text to a number

Whatever the person types, input() returns text. "12" and "30" are two texts, and + between texts glues them together. To do math, turn the text into a number:

first = int(input())
second = int(input())
total = first + second
print(f"Total: €{total}")
Input
12
30
Output
Total: €42

Turning text into a value of another type is called parsing.

  • int(...) gives an int.
  • float(...) gives a float.
  • The opposite, from a number to text, is done by str(...).

The total goes into the text with an f-string, because Python does not glue text and a number together.

The sum here is the first calculation in the course. Subtraction, multiplication and division come in the next lesson.

first = int(input())
second = int(input())
total = first + second
print(f"Total: €{total}")
Step by step, in words
  1. The person types 12 and Enter. input() returns the text "12", not a number.
  2. int turns the text into the number 12. It goes into first.
  3. 30 takes the same path: text, parsing, a number in second.
  4. Now + adds numbers: 12 + 30 = 42.
  5. It prints "Total: €42".
More precisely, if you are curious
  • If the text is not a number (for example "twelve"), the program stops with ValueError. Spaces around it do not matter: int(" 12 ") is 12. You will see how to catch such an error in the "Errors and exceptions" module.
print(int(" 12 "))
print(float("3.5"))
print(int("twelve"))
Output
12
3.5
Traceback (most recent call last):
File "/home/student/sum.py", line 3, in <module>
print(int("twelve"))
^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'twelve'
  • float always wants a point, whatever the computer's settings: float("3,5") stops with ValueError. int("3.5") stops too: a decimal number is not a whole number.

Try it

How many tickets?

The program reads how many adults and how many children there are.

Input
2
3

What will the program print?

adults = int(input())
children = int(input())
print("Tickets: " + adults + children)
Answer

The idea

Numbers the way you want them

In the last lesson the price 49.90 came out as 49.9. For a price you always want two digits after the decimal point. This is formatted output:

product = "Headphones"
price = 49.9
qty = 2
print(f"{product}: €{price:.2f}")
print(f"{qty} in the cart")
label = f"Price: €{price:.2f}"
print(label)
Output
Headphones: €49.90
2 in the cart
Price: €49.90

You already know the f-string: the values are in curly braces, {product}. This is called string interpolation.

After the value there can be a colon and a format: {price:.2f} means a decimal number with exactly 2 digits after the point. .0f has no digits after the point, .3f has three.

An f-string is not only for printing. label = f"…" stores the finished text in a variable.

The value in the variable does not change. The format only decides how it looks when it is printed.

More precisely, if you are curious
  • Thousands separators and lining up in columns:
total = 1234.5
print(f"Total: €{total:,.2f}")
print(f"{'Coffee':<10}|{2.5:8.2f}")
print(f"{'Laptop':<10}|{1299.0:8.2f}")
Output
Total: €1,234.50
Coffee | 2.50
Laptop | 1299.00

, adds a thousands separator. The number before the point is the width: {2.5:8.2f} takes 8 characters, aligned right, and {'Coffee':<10} takes 10, aligned left (<).

  • f-strings do not follow the regional settings: a point stays a point on every computer. If you want a decimal comma, the way it is written in Bulgaria and much of Europe, add it yourself:
price = 49.9
print(f"Price: €{price:.2f}".replace(".", ","))
Output
Price: €49,90

Try it

Two digits

A night at the hotel costs €65.5. You want it to come out as "Per night: €65.50". What goes in the blank?

print(f"Per night: €{price:}")

Try it

Find the bug

12 tickets are already reserved, and the program adds as many more as you enter. With input 4 it stops on line 3 with TypeError: unsupported operand type(s) for +: 'int' and 'str'. Which line is the bug on?

Pick the line with the bug.

Exercise

Programs that ask

Solve the tasks in your editor. The input is one line for each value. Do not print questions like "Enter a name:", so your output matches the sample: write input() with nothing in the parentheses.

1. Greeting by name. Read a name and greet the person.

Input
Maria
Output
Hello, Maria!

2. Sum of two numbers. Read two whole numbers and print the calculation.

Input
17
25
Output
17 + 25 = 42

3. Two texts in one. Read two texts and print them together, with a space between them.

Input
Veliko
Tarnovo
Output
Veliko Tarnovo

4. π with two digits. Store π in a variable as 3.14159265358979 and print it with two digits after the point. The ready value math.pi comes in the next lesson.

Output
3.14

More tasks

  • Age. Read a name and an age (a whole number) and print "Maria is 19 years old."
  • A business card from the keyboard. Read a name, a job and a phone number and print the business card from the "Your first program" lesson with them.
  • A price with two digits. Read a price as a decimal number and print it with two digits and the euro sign: for input 7.5 the output is Price: €7.50.
  • Sum of two prices. Read two decimal prices and print their sum with two digits: for input 12.4 and 3.15 the output is Total: €15.55.

Test

Check yourself

1. What does input() return?
2. You read the texts "12" and "30". What does first + second give?
3. What does int("25") do?
4. a = 2, b = 3. What does print("Sum: " + a + b) do?
5. How do you print 7.5 as 7.50?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·