
Bug hunt
Mixing Types
Python won't guess what you mean when you mix text and numbers:
print("5" + 1) # TypeError!
Should that be 6 or "51"? Python refuses to guess, so it
raises a TypeError. You decide by converting the value:
| Function | Turns a value into… | Example | Result |
|---|---|---|---|
int() |
a whole number | int("5") |
5 |
float() |
a decimal number | float("2.5") |
2.5 |
str() |
text | str(5) |
"5" |
print(int("5") + 1) # 6
print("5" + str(1)) # 51
Pip tip:
int("hello")fails too. Python can only convert text that actually looks like a number.
Assignment
The lighthouse log stores numbers as text, and this program crashes. Fix it so it prints:
The lighthouse turns 101 next year
next_yearshould be the number101. Convertagewithint().- The message line glues text with a number. Convert the number with
str().
The lighthouse log stores numbers as text, and this program crashes. Fix it so it prints:
The lighthouse turns 101 next year
next_yearshould be the number101. Convertagewithint().- The message line glues text with a number. Convert the number with
str().
main.py Python sleeping
Press Run to try your code, then Check to test it.