Type casting
Text that looks like a number is still text:
print("5" + "5") # 55 (strings glue together) print(5 + 5) # 10
Casting converts between types: int("12") makes 12, float("2.5") makes 2.5, and str(42) makes "42".
After casting to numbers, * multiplies (2 * 3 is 6) and / divides (6 / 2 is 3.0).
You cannot glue a str and an int with +. Convert the number with str() first.
See it run
seats = "4" extra = 2 total = int(seats) + extra label = "Seats: " + str(total) print(label)
seats is text and extra is a number. Watch how int() and str() convert between them.
Practice type casting
Exercise 1
a and b arrived from a web form as text.
- Make
totaltheir numeric sum (42, an int). - Make
messageequal to"Total: 42"by joining text withstr(total), then print it.
Exercise 2
A ribbon order arrives as length = "2.5" and pieces = "4". Convert them to compute float metres = 10.0. Build and print label = "Metres: 10.0" using str().
Exercise 3
A bus fare form sends fare = "3.75" and paid = "10". Compute float change and print message = "Change: 6.25" by joining text with str(change).
Free lesson: use the editor to practice it.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.