Page3/20
Variables & Data Types Β· Page 3 of 5
Type Conversion (Casting)
Converting Between Types
Sometimes you need to change a variable's type. Python makes this easy with conversion functions.
Converting TO String
Use str() to turn anything into text.
age = 28
age_text = str(age) # "28"
score = 95.5
score_text = str(score) # "95.5"
result = True
result_text = str(result) # "True"
Why? When you want to combine numbers with text:
name = "Alice"
age = 28
# This FAILS: print("My name is " + name + age) β
# But this WORKS:
print("My name is " + name + " and I'm " + str(age)) β
Converting TO Integer
Use int() to get whole numbers. Decimals are truncated (not rounded)!
score = "95"
score_int = int(score) # 95
price = 19.99
price_int = int(price) # 19 (truncated, not rounded!)
bool_value = True
bool_int = int(bool_value) # 1
Converting TO Float
Use float() to get decimal numbers.
age = 28
age_float = float(age) # 28.0
score = "95.5"
score_float = float(score) # 95.5
Converting TO Boolean
Use bool(). Most values are True, but some are special "falsy" values:
bool(1) # True
bool(0) # False β special case!
bool("hello") # True
bool("") # False β empty string is falsy!
bool([]) # False β empty list is falsy!
Real-World Example: Calculating Totals
# User input comes as text (strings)
price_str = "19.99"
quantity_str = "3"
# Convert to numbers for math
price = float(price_str)
quantity = int(quantity_str)
# Calculate total
total = price * quantity # 59.97
# Convert back to string for display
print(f"Total: ${str(total)}")
Insight: This pattern (string β number β string) happens constantly in real programs!
main.py
Loading...
OUTPUT
βΆClick "Run Code" to executeβ¦