Text and input
Part of the free LogicWiz Python course, Module 1: Start coding. The examples and practice run in the app.
Meher typed 2 samosas and 3 chais, and the app said she ordered 23 items. Nothing crashed. So what went wrong?
You'll learn to
- Make strings, join them with +, repeat them with *, and measure them with len()
- Read what the user types with input()
- Turn text into numbers with int() and float(), and back with str()
- Expect the surprises: 0.1 + 0.2, and // and % with negative numbers
Learn
Text is a string
Anything inside quotes is a string (text). "chai" and 'chai' are the same.
Use double quotes when the text has an apostrophe: "Meher's order".
"15" is a string too. It looks like a number, but to Python it is two characters, 1 and 5.
Joining, repeating, measuring
first = "Meher"
greet = "Hi " + first
print(greet)
print("ha" * 3)
print(len(greet))
print("Line 1\nLine 2")
print("-" * 20)
+ joins strings, * repeats them, len() counts characters (spaces count too). \n inside a string is a new line character.
input() reads what the user types
a = input("Samosas? ")
b = input("Chais? ")
print(a + b)
print(int(a) + int(b))
Here the box types 2 and 3 for you. a + b joined the text "2" and "3" into "23". int() turned them into numbers first, so the second line is 5.
input() always gives you a string, even when the user types a number. Wrap it: int(input()) for whole numbers, float(input()) for decimals like 12.5. In the practice tasks, use input() without prompt text so your output matches exactly.
Converting between types
price = float("12.5")
qty = int("4")
print(price * qty)
print("Total: Rs " + str(50))
print(int(7.9))
print(int(" 42 "))
str() turns a number into text so you can join it. int(7.9) cuts off the decimal (7, it does not round). int("12.5") is an error: convert with float() first.
Decimals are slightly off
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
print(7 // 2, -7 // 2)
print(7 % 3, -7 % 3)
Computers store decimals in binary, so 0.1 + 0.2 is a hair off. Round money before printing. // rounds down (towards minus infinity), so -7 // 2 is -4, and -7 % 3 is 2 so that 3 * (-3) + 2 = -7 still holds.
CBSE asks for the output of -7 // 2 (-4), "5" + "3" ("53") and "ab" * 3. Learn this error too: TypeError: can only concatenate str (not "int") to str. It means you tried "text" + number; use str(number) or a comma in print.
In one line
input() returns text; wrap it in int() or float() before doing maths, and str() a number before joining it to text.