Type conversion (also called type casting) changes a value from one data type to another. Python provides built-in functions to do this safely.
Why convert types?
Different operations require specific types. For example, you cannot add a string and an integer directly.
Common situations:
- Converting user input (always string) to numbers
- Combining numbers into text
- Working with different data sources
Common conversion functions
-
int()→ converts to integer (whole number)
text = "25"
age = int(text)
print(age + 5) # 30
-
float()→ converts to floating-point number (with decimals)
price_text = "19.99"
price = float(price_text)
print(price + 0.01) # 20.0
-
str()→ converts anything to string
score = 95
message = "Your score: " + str(score)
print(message) # Your score: 95
-
bool()→ converts to True or False
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False (empty string)
print(bool("hi")) # True
Examples in action
Convert input for calculations:
height_cm = input("Enter height in cm: ")
height_m = float(height_cm) / 100
print(f"Height in meters: {height_m}")
Build messages with mixed types:
items = 3
total = 45.50
summary = f"You bought {items} items for ${total}"
print(summary)
When conversion fails
Some conversions raise errors:
int("hello") # ValueError: invalid literal for int()
Always handle possible errors in real programs (covered in later topics).
Quick summary
- Use
int()for whole numbers. - Use
float()for decimal numbers. - Use
str()to turn values into text. - Use
bool()to get True/False. - Convert types when mixing different data.
Practice converting between types in small scripts. Type conversion is essential for working with real data in Python programs.
Top comments (1)
Perfeito