Module 2: Python Basic Syntax and Data Types
Typecasting
Typecasting means converting a value from one type to another — like turning text "42" into the number 42.
About 8 minutes
Why cast types?
input() always returns a string. If you want to do math on what the user typed, you must convert to int or float first.
"25"
string from input
int()
convert
25
number
Common conversion functions
- int(x) — whole number
- float(x) — decimal number
- str(x) — text
- bool(x) — True or False
Example code
text_age = "21" age = int(text_age) print(age + 1) # 22 price = 9.99 print(str(price)) # "9.99" as text
int("hello") will cause an error — you can only cast strings that look like numbers.
Practice
Convert the string variables to numbers, add them, and print the result.
Key takeaways
- Use int(), float(), str(), bool() to convert types.
- input() gives strings — cast before math.
- Invalid conversions raise errors; use sensible input.
Quick check: Typecasting
Question 1 of 2
What does int("8") give you?