Input, output and type conversion
Read values typed by the user with input(), convert them with int() and float(), print the result with an f-string, and say which error a mistake gives.
It opens on
The user types 1.1 for the price and 3 for how many. Will print(price + qty) show 4.1, 1.13 or an error?
Why it matters
A program is only useful if it can take in what a person types, and everything typed arrives as text, so unconverted input gives a silently wrong answer or a crash that every beginner meets in the first week.
Good to know first
- Values, types and expressions: int, float and str, + joins two str, and a mix of str and int in an operator gives a TypeError
- Variables and assignment: price = input(...) binds the name to the value of the right side
Step by step
What input gives back
Say what input() returns for any typed text, and trace a program that uses it without conversion.
With 1.1 and 3 the same thing happens, so the program prints 1.13, which is neither 4.1 nor an error, since plus on two strings joins them.
a note on each line with the values
A common mix-up
Digits typed by the user are numbers, so price + qty is 4.1.
In fact: Input always gives a str, and plus on two strings joins them into 1.13.
Converting text to numbers
Convert typed text with int() and float(), say the type of the result, and name the ValueError a wrong text gives.
When the user types 1.1, input gives '1.1' and float turns it into the float 1.1; when the user types 3, input gives '3' and int turns it into the int 3.
the first two rows of the table
A common mix-up
Int("2.5") should give 2, as int(2.5) does.
In fact: Int on a str accepts only whole-number text, so int("2.5") is a ValueError; only int on a float cuts off the decimals.
Printing the result
Print a line that mixes text and values with an f-string, formatting a float to two decimals, and say what a plus between a str and a number does.
With pencil, 1.1 and 3 typed, {qty} becomes 3 and {item} becomes pencil, and {price * qty:.2f} works out 1.1 * 3, then the .2f keeps two digits after the decimal point, so the line printed is 3 x pencil = 3.30.
the run
A common mix-up
A plus between text and a number joins them, so "Total" + price * qty works.
In fact: Plus joins only two strings; a str and a float give a TypeError, so use a comma or an f-string.
Try it
The user types 8 for price and 4 for qty. What does print(price + qty) show, and what does print(price * qty) do?Answer
84 and a TypeError
Hint: Both are strings
Suppose the user types 5 and then 2. What does print(price + qty) show?Answer
52, because plus joins the two strings 5 and 2 and adds nothing.
Suppose the user types 4 for the price. What does float("4") give?Answer
4.0, a float, even though 4 was typed with no decimal point.
With the same typed values, what would f"{qty * 2} {item}s" print?Answer
6 pencils, since the braces work out qty * 2 as 6 and write item as pencil.
