Getting started · Lesson 4 of 25
Type conversion and input
int, float and str, and why input always returns text.
7 minutes3 games
int("42"), float("3.5"), str(99) and bool(0) convert between types. It matters with input(): it reads what the user types and always returns text, even when they type a number.
Python
age = input("How old are you? ") # the user types 20
print(age + 1) # TypeError: can only concatenate str to str
print(int(age) + 1) # 21Python
print(int("42") + 8)
print(float("2.5") * 2)
print("Score: " + str(95))
print(int(3.99)) # cuts the decimals: 3
print(bool(""), bool("0"), bool(0), bool([]))
try:
int("12px")
except ValueError as e:
print("ValueError:", e)falsy values =
False[0]
0[1]
0.0[2]
""[3]
[][4]
{}[5]
None[6]
These count as False in conditions; everything else is True.
What's the output?
print(int("7") + int("3"))
print("7" + "3")What will this code print?
Spot the bug
One line raises a TypeError. Which?
Exercise
Both values arrive as text. Print their sum as a number (30).
Expected output: 30
Python
a = "12" b = "18"
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.