Input and output
Problem
The program knows only one name
The program greets the customer by name:
name = "Maria"print("Hello, " + name + "!")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.
name = input("What is your name? ")print("Hello, " + name + "!")MariaWhat 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 withEOFError.
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 + secondprint("Total: €" + total)1230Total: €1230Instead 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 + secondprint(f"Total: €{total}")1230Total: €42Turning text into a value of another type is called parsing.
int(...)gives anint.float(...)gives afloat.- 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 + secondprint(f"Total: €{total}")Step by step, in words
- The person types 12 and Enter. input() returns the text "12", not a number.
- int turns the text into the number 12. It goes into first.
- 30 takes the same path: text, parsing, a number in second.
- Now + adds numbers: 12 + 30 = 42.
- 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"))123.5Traceback (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'floatalways wants a point, whatever the computer's settings:float("3,5")stops withValueError.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.
23What will the program print?
adults = int(input())children = int(input())print("Tickets: " + adults + children)"Tickets: " + adults, text + a number. Python does not glue text and a number together, and it stops: TypeError: can only concatenate str (not "int") to str. The sum goes into the text with an f-string: f"Tickets: {adults + children}" gives "Tickets: 5".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.9qty = 2print(f"{product}: €{price:.2f}")print(f"{qty} in the cart")label = f"Price: €{price:.2f}"print(label)Headphones: €49.902 in the cartPrice: €49.90You 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.5print(f"Total: €{total:,.2f}")print(f"{'Coffee':<10}|{2.5:8.2f}")print(f"{'Laptop':<10}|{1299.0:8.2f}")Total: €1,234.50Coffee | 2.50Laptop | 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.9print(f"Price: €{price:.2f}".replace(".", ","))Price: €49,90Try 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:}").2f: a decimal number with exactly two digits after the point.
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.
input() returns text, "4". On line 3 a number is added to text, and Python stops there. But the bug is earlier: what was read was never turned into a number. The fix is tickets = int(input("Number of tickets: ")).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.
MariaHello, Maria!2. Sum of two numbers. Read two whole numbers and print the calculation.
172517 + 25 = 423. Two texts in one. Read two texts and print them together, with a space between them.
VelikoTarnovoVeliko Tarnovo4. π 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.
3.14More 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.5the output isPrice: €7.50. - Sum of two prices. Read two decimal prices and print their sum with two digits: for input
12.4and3.15the output isTotal: €15.55.
Test