2. Data Types and Operators
2.3 Type conversion
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
Type conversion is a magic wand. It turns text "12" into the real number 12.
- int() makes a whole number.
- float() makes a decimal number.
- str() turns a number back into text.
Thumb rule: Data from files comes as text. Use int() before doing maths.
Watch it run · 1
print(int("12") + 3)15
Watch it run · 2
print(str(5) + "0")50
Data from files usually arrives as text, even when it looks like a number. " 12 " from a CSV is a string with spaces. Convert it before doing maths.
int("12")→12float("4.5")→4.5str(12)→"12"" 12 ".strip()→"12"(removes spaces around the text)
If the text isn’t a valid number, such as int("unknown"), Python stops with a ValueError. Later you’ll learn to catch that error and record the bad rows.
Clean, then convert
raw = " 12 "clean = raw.strip()→"12"units = int(clean)→12
int("4.5") fails with ValueError. Use float("4.5") for decimal text, then int() if you need a whole number: int(float("4.5")) is 4.
How it fits together
- " 12 " (text)
- .strip() → "12"
- int() → 12
Step through the code
Python
raw_units = " 12 "units = int(raw_units.strip())print(units + 3)
Output
15
Practice in Python ✓ Solved
Convert raw_units to an integer, double it, and print the result.
Expected output
18
Reference solution
raw_units = " 9 "
print(int(raw_units.strip()) * 2)
Question 1 · Easy
What does int("25") + 5 give?
Question 2 · Medium
What does str(7) + "0" give?
Question 3 · Hard
What does int(" 8 ") give?
Key takeaways
Convert incoming fields deliberately before using them in calculations.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in