Data Types
Type Conversion
Changing Data Types
A web form returns the user's age as text: "25". To check if they're old enough to vote (age >= 18), you need to convert "25" to the number 25. Type conversion bridges the gap between data formats.
Int to float (precise division)
When dividing integers, you might want a decimal result.
a = 7
b = 3
# Python 3: / always returns float
result = a / b
print(f"Division: {a}/{b} = {result}")
# Integer division with //
int_result = a // b
print(f"Integer division: {a}//{b} = {int_result}")
# Explicit conversion (not needed in Python 3 for division)
float_result = float(a) / float(b)
print(f"Explicit float: {float_result}")
# Practical: calculate percentage
score = 85
total = 100
percentage = score / total * 100
print(f"Percentage: {percentage}%")
a = 5
b = 3
# Python 3: / always returns float
result = a / b
print(f"Division: {a}/{b} = {result}")
# Integer division with //
int_result = a // b
print(f"Integer division: {a}//{b} = {int_result}")
# Explicit conversion (not needed in Python 3 for division)
float_result = float(a) / float(b)
print(f"Explicit float: {float_result}")
# Practical: calculate percentage
score = 85
total = 100
percentage = score / total * 100
print(f"Percentage: {percentage}%")
a = 10
b = 3
# Python 3: / always returns float
result = a / b
print(f"Division: {a}/{b} = {result}")
# Integer division with //
int_result = a // b
print(f"Integer division: {a}//{b} = {int_result}")
# Explicit conversion (not needed in Python 3 for division)
float_result = float(a) / float(b)
print(f"Explicit float: {float_result}")
# Practical: calculate percentage
score = 85
total = 100
percentage = score / total * 100
print(f"Percentage: {percentage}%")
a = 7
b = 2
# Python 3: / always returns float
result = a / b
print(f"Division: {a}/{b} = {result}")
# Integer division with //
int_result = a // b
print(f"Integer division: {a}//{b} = {int_result}")
# Explicit conversion (not needed in Python 3 for division)
float_result = float(a) / float(b)
print(f"Explicit float: {float_result}")
# Practical: calculate percentage
score = 85
total = 100
percentage = score / total * 100
print(f"Percentage: {percentage}%")
a = 7
b = 4
# Python 3: / always returns float
result = a / b
print(f"Division: {a}/{b} = {result}")
# Integer division with //
int_result = a // b
print(f"Integer division: {a}//{b} = {int_result}")
# Explicit conversion (not needed in Python 3 for division)
float_result = float(a) / float(b)
print(f"Explicit float: {float_result}")
# Practical: calculate percentage
score = 85
total = 100
percentage = score / total * 100
print(f"Percentage: {percentage}%")
a ← 7, b ← 3, result ← 2.3333333333333335, int_result ← 2, float_result ← 2.3333333333333335
1a→ 7 = 7 #@a=5, 102b→ 3 = 3 #@b=2, 434# Python 3: / always returns float5result→ 2.3333333333333335 = a7 / b36print(f"Division: {a7}/{b3} = {result2.3333333333333335}")78# Integer division with //9int_result→ 2 = a7 // b310print(f"Integer division: {a7}//{b3} = {int_result2}")1112# Explicit conversion (not needed in Python 3 for division)13float_result→ 2.3333333333333335 = float(a7) / float(b3)14print(f"Explicit float: {float_result2.3333333333333335}")1516# Practical: calculate percentage17score→ 85 = 8518total→ 100 = 10019percentage→ 85.0 = score85 / total100 * 10020print(f"Percentage: {percentage85.0}%")outputDivision: 7/3 = 2.3333333333333335 Integer division: 7//3 = 2 Explicit float: 2.3333333333333335 Percentage: 85.0%
a ← 5, b ← 3, result ← 1.6666666666666667, int_result ← 1, float_result ← 1.6666666666666667
1a→ 5 = 52b→ 3 = 334# Python 3: / always returns float5result→ 1.6666666666666667 = a5 / b36print(f"Division: {a5}/{b3} = {result1.6666666666666667}")78# Integer division with //9int_result→ 1 = a5 // b310print(f"Integer division: {a5}//{b3} = {int_result1}")1112# Explicit conversion (not needed in Python 3 for division)13float_result→ 1.6666666666666667 = float(a5) / float(b3)14print(f"Explicit float: {float_result1.6666666666666667}")1516# Practical: calculate percentage17score→ 85 = 8518total→ 100 = 10019percentage→ 85.0 = score85 / total100 * 10020print(f"Percentage: {percentage85.0}%")outputDivision: 5/3 = 1.6666666666666667 Integer division: 5//3 = 1 Explicit float: 1.6666666666666667 Percentage: 85.0%
a ← 10, b ← 3, result ← 3.3333333333333335, int_result ← 3, float_result ← 3.3333333333333335
1a→ 10 = 102b→ 3 = 334# Python 3: / always returns float5result→ 3.3333333333333335 = a10 / b36print(f"Division: {a10}/{b3} = {result3.3333333333333335}")78# Integer division with //9int_result→ 3 = a10 // b310print(f"Integer division: {a10}//{b3} = {int_result3}")1112# Explicit conversion (not needed in Python 3 for division)13float_result→ 3.3333333333333335 = float(a10) / float(b3)14print(f"Explicit float: {float_result3.3333333333333335}")1516# Practical: calculate percentage17score→ 85 = 8518total→ 100 = 10019percentage→ 85.0 = score85 / total100 * 10020print(f"Percentage: {percentage85.0}%")outputDivision: 10/3 = 3.3333333333333335 Integer division: 10//3 = 3 Explicit float: 3.3333333333333335 Percentage: 85.0%
a ← 7, b ← 2, result ← 3.5, int_result ← 3, float_result ← 3.5
1a→ 7 = 72b→ 2 = 234# Python 3: / always returns float5result→ 3.5 = a7 / b26print(f"Division: {a7}/{b2} = {result3.5}")78# Integer division with //9int_result→ 3 = a7 // b210print(f"Integer division: {a7}//{b2} = {int_result3}")1112# Explicit conversion (not needed in Python 3 for division)13float_result→ 3.5 = float(a7) / float(b2)14print(f"Explicit float: {float_result3.5}")1516# Practical: calculate percentage17score→ 85 = 8518total→ 100 = 10019percentage→ 85.0 = score85 / total100 * 10020print(f"Percentage: {percentage85.0}%")outputDivision: 7/2 = 3.5 Integer division: 7//2 = 3 Explicit float: 3.5 Percentage: 85.0%
a ← 7, b ← 4, result ← 1.75, int_result ← 1, float_result ← 1.75
1a→ 7 = 72b→ 4 = 434# Python 3: / always returns float5result→ 1.75 = a7 / b46print(f"Division: {a7}/{b4} = {result1.75}")78# Integer division with //9int_result→ 1 = a7 // b410print(f"Integer division: {a7}//{b4} = {int_result1}")1112# Explicit conversion (not needed in Python 3 for division)13float_result→ 1.75 = float(a7) / float(b4)14print(f"Explicit float: {float_result1.75}")1516# Practical: calculate percentage17score→ 85 = 8518total→ 100 = 10019percentage→ 85.0 = score85 / total100 * 10020print(f"Percentage: {percentage85.0}%")outputDivision: 7/4 = 1.75 Integer division: 7//4 = 1 Explicit float: 1.75 Percentage: 85.0%
Python 3's / operator always returns float. Use // for integer division.
Float to int (truncation)
Sometimes you need a whole number from a decimal.
price = 19.99
# int() truncates (drops decimals)
truncated = int(price)
print(f"Price: {price}")
print(f"Truncated: {truncated}")
# round() rounds to nearest
rounded = round(price)
print(f"Rounded: {rounded}")
# round() can specify decimal places
two_decimals = round(price, 1)
print(f"One decimal: {two_decimals}")
# Floor and ceiling
import math
floor_val = math.floor(price)
ceiling_val = math.ceil(price)
print(f"Floor: {floor_val}")
print(f"Ceiling: {ceiling_val}")
# Practical: convert dollars to cents (avoid floating point)
cents = round(price * 100)
print(f"Cents: {cents}")
price = 25.50
# int() truncates (drops decimals)
truncated = int(price)
print(f"Price: {price}")
print(f"Truncated: {truncated}")
# round() rounds to nearest
rounded = round(price)
print(f"Rounded: {rounded}")
# round() can specify decimal places
two_decimals = round(price, 1)
print(f"One decimal: {two_decimals}")
# Floor and ceiling
import math
floor_val = math.floor(price)
ceiling_val = math.ceil(price)
print(f"Floor: {floor_val}")
print(f"Ceiling: {ceiling_val}")
# Practical: convert dollars to cents (avoid floating point)
cents = round(price * 100)
print(f"Cents: {cents}")
price = 9.95
# int() truncates (drops decimals)
truncated = int(price)
print(f"Price: {price}")
print(f"Truncated: {truncated}")
# round() rounds to nearest
rounded = round(price)
print(f"Rounded: {rounded}")
# round() can specify decimal places
two_decimals = round(price, 1)
print(f"One decimal: {two_decimals}")
# Floor and ceiling
import math
floor_val = math.floor(price)
ceiling_val = math.ceil(price)
print(f"Floor: {floor_val}")
print(f"Ceiling: {ceiling_val}")
# Practical: convert dollars to cents (avoid floating point)
cents = round(price * 100)
print(f"Cents: {cents}")
price ← 19.99, truncated ← 19, rounded ← 20, two_decimals ← 20.0
1price→ 19.99 = 19.99 #@price=25.50, 9.9523# int() truncates (drops decimals)4truncated→ 19 = int(price19.99)5print(f"Price: {price19.99}")6print(f"Truncated: {truncated19}")78# round() rounds to nearest9rounded→ 20 = round(price19.99)10print(f"Rounded: {rounded20}")1112# round() can specify decimal places13two_decimals→ 20.0 = round(price19.99, 1)14print(f"One decimal: {two_decimals20.0}")1516# Floor and ceiling17import math18floor_val→ 19 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.floor(price19.99)19ceiling_val→ 20 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.ceil(price19.99)20print(f"Floor: {floor_val19}")21print(f"Ceiling: {ceiling_val20}")2223# Practical: convert dollars to cents (avoid floating point)24cents→ 1999 = round(price19.99 * 100)25print(f"Cents: {cents1999}")outputPrice: 19.99 Truncated: 19 Rounded: 20 One decimal: 20.0 Floor: 19 Ceiling: 20 Cents: 1999
price ← 25.5, truncated ← 25, rounded ← 26, two_decimals ← 25.5
1price→ 25.5 = 25.5023# int() truncates (drops decimals)4truncated→ 25 = int(price25.5)5print(f"Price: {price25.5}")6print(f"Truncated: {truncated25}")78# round() rounds to nearest9rounded→ 26 = round(price25.5)10print(f"Rounded: {rounded26}")1112# round() can specify decimal places13two_decimals→ 25.5 = round(price25.5, 1)14print(f"One decimal: {two_decimals25.5}")1516# Floor and ceiling17import math18floor_val→ 25 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.floor(price25.5)19ceiling_val→ 26 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.ceil(price25.5)20print(f"Floor: {floor_val25}")21print(f"Ceiling: {ceiling_val26}")2223# Practical: convert dollars to cents (avoid floating point)24cents→ 2550 = round(price25.5 * 100)25print(f"Cents: {cents2550}")outputPrice: 25.5 Truncated: 25 Rounded: 26 One decimal: 25.5 Floor: 25 Ceiling: 26 Cents: 2550
price ← 9.95, truncated ← 9, rounded ← 10, two_decimals ← 9.9
1price→ 9.95 = 9.9523# int() truncates (drops decimals)4truncated→ 9 = int(price9.95)5print(f"Price: {price9.95}")6print(f"Truncated: {truncated9}")78# round() rounds to nearest9rounded→ 10 = round(price9.95)10print(f"Rounded: {rounded10}")1112# round() can specify decimal places13two_decimals→ 9.9 = round(price9.95, 1)14print(f"One decimal: {two_decimals9.9}")1516# Floor and ceiling17import math18floor_val→ 9 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.floor(price9.95)19ceiling_val→ 10 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.ceil(price9.95)20print(f"Floor: {floor_val9}")21print(f"Ceiling: {ceiling_val10}")2223# Practical: convert dollars to cents (avoid floating point)24cents→ 995 = round(price9.95 * 100)25print(f"Cents: {cents995}")outputPrice: 9.95 Truncated: 9 Rounded: 10 One decimal: 9.9 Floor: 9 Ceiling: 10 Cents: 995
String to number (parse input)
User input is text. Convert to numbers for calculation.
# Simulated user input
age_input = "25"
price_input = "19.99"
# Parse string to number
age = int(age_input)
price = float(price_input)
print(f"Age string: {age_input}")
print(f"Age number: {age}")
print(f"Age + 1 = {age + 1}")
print(f"Price string: {price_input}")
print(f"Price number: {price}")
print(f"With tax: {price * 1.1}")
# Complex number from string
complex_str = "3+4j"
c = complex(complex_str)
print(f"Complex: {c}, magnitude: {abs(c)}")
# Simulated user input
age_input = "30"
price_input = "19.99"
# Parse string to number
age = int(age_input)
price = float(price_input)
print(f"Age string: {age_input}")
print(f"Age number: {age}")
print(f"Age + 1 = {age + 1}")
print(f"Price string: {price_input}")
print(f"Price number: {price}")
print(f"With tax: {price * 1.1}")
# Complex number from string
complex_str = "3+4j"
c = complex(complex_str)
print(f"Complex: {c}, magnitude: {abs(c)}")
# Simulated user input
age_input = "17"
price_input = "19.99"
# Parse string to number
age = int(age_input)
price = float(price_input)
print(f"Age string: {age_input}")
print(f"Age number: {age}")
print(f"Age + 1 = {age + 1}")
print(f"Price string: {price_input}")
print(f"Price number: {price}")
print(f"With tax: {price * 1.1}")
# Complex number from string
complex_str = "3+4j"
c = complex(complex_str)
print(f"Complex: {c}, magnitude: {abs(c)}")
# Simulated user input
age_input = "25"
price_input = "9.95"
# Parse string to number
age = int(age_input)
price = float(price_input)
print(f"Age string: {age_input}")
print(f"Age number: {age}")
print(f"Age + 1 = {age + 1}")
print(f"Price string: {price_input}")
print(f"Price number: {price}")
print(f"With tax: {price * 1.1}")
# Complex number from string
complex_str = "3+4j"
c = complex(complex_str)
print(f"Complex: {c}, magnitude: {abs(c)}")
# Simulated user input
age_input = "25"
price_input = "100.00"
# Parse string to number
age = int(age_input)
price = float(price_input)
print(f"Age string: {age_input}")
print(f"Age number: {age}")
print(f"Age + 1 = {age + 1}")
print(f"Price string: {price_input}")
print(f"Price number: {price}")
print(f"With tax: {price * 1.1}")
# Complex number from string
complex_str = "3+4j"
c = complex(complex_str)
print(f"Complex: {c}, magnitude: {abs(c)}")
age_input ← 25, price_input ← 19.99, age ← 25, price ← 19.99, complex_str ← 3+4j
1# Simulated user input2age_input→ 25 = "25" #@age_input="30", "17"3price_input→ 19.99 = "19.99" #@price_input="9.95", "100.00"45# Parse string to number6age→ 25 = int(age_input25)7price→ 19.99 = float(price_input19.99)89print(f"Age string: {age_input25}")10print(f"Age number: {age25}")11print(f"Age + 1 = {age25 + 1}")1213print(f"Price string: {price_input19.99}")14print(f"Price number: {price19.99}")15print(f"With tax: {price19.99 * 1.1}")1617# Complex number from string18complex_str→ 3+4j = "3+4j"19c→ (3+4j) = complex(complex_str3+4j)20print(f"Complex: {c(3+4j)}, magnitude: {abs(c)}")outputAge string: 25 Age number: 25 Age + 1 = 26 Price string: 19.99 Price number: 19.99 With tax: 21.989 Complex: (3+4j), magnitude: 5.0
age_input ← 30, price_input ← 19.99, age ← 30, price ← 19.99, complex_str ← 3+4j
1# Simulated user input2age_input→ 30 = "30"3price_input→ 19.99 = "19.99"45# Parse string to number6age→ 30 = int(age_input30)7price→ 19.99 = float(price_input19.99)89print(f"Age string: {age_input30}")10print(f"Age number: {age30}")11print(f"Age + 1 = {age30 + 1}")1213print(f"Price string: {price_input19.99}")14print(f"Price number: {price19.99}")15print(f"With tax: {price19.99 * 1.1}")1617# Complex number from string18complex_str→ 3+4j = "3+4j"19c→ (3+4j) = complex(complex_str3+4j)20print(f"Complex: {c(3+4j)}, magnitude: {abs(c)}")outputAge string: 30 Age number: 30 Age + 1 = 31 Price string: 19.99 Price number: 19.99 With tax: 21.989 Complex: (3+4j), magnitude: 5.0
age_input ← 17, price_input ← 19.99, age ← 17, price ← 19.99, complex_str ← 3+4j
1# Simulated user input2age_input→ 17 = "17"3price_input→ 19.99 = "19.99"45# Parse string to number6age→ 17 = int(age_input17)7price→ 19.99 = float(price_input19.99)89print(f"Age string: {age_input17}")10print(f"Age number: {age17}")11print(f"Age + 1 = {age17 + 1}")1213print(f"Price string: {price_input19.99}")14print(f"Price number: {price19.99}")15print(f"With tax: {price19.99 * 1.1}")1617# Complex number from string18complex_str→ 3+4j = "3+4j"19c→ (3+4j) = complex(complex_str3+4j)20print(f"Complex: {c(3+4j)}, magnitude: {abs(c)}")outputAge string: 17 Age number: 17 Age + 1 = 18 Price string: 19.99 Price number: 19.99 With tax: 21.989 Complex: (3+4j), magnitude: 5.0
age_input ← 25, price_input ← 9.95, age ← 25, price ← 9.95, complex_str ← 3+4j
1# Simulated user input2age_input→ 25 = "25"3price_input→ 9.95 = "9.95"45# Parse string to number6age→ 25 = int(age_input25)7price→ 9.95 = float(price_input9.95)89print(f"Age string: {age_input25}")10print(f"Age number: {age25}")11print(f"Age + 1 = {age25 + 1}")1213print(f"Price string: {price_input9.95}")14print(f"Price number: {price9.95}")15print(f"With tax: {price9.95 * 1.1}")1617# Complex number from string18complex_str→ 3+4j = "3+4j"19c→ (3+4j) = complex(complex_str3+4j)20print(f"Complex: {c(3+4j)}, magnitude: {abs(c)}")outputAge string: 25 Age number: 25 Age + 1 = 26 Price string: 9.95 Price number: 9.95 With tax: 10.945 Complex: (3+4j), magnitude: 5.0
age_input ← 25, price_input ← 100.00, age ← 25, price ← 100.0
1# Simulated user input2age_input→ 25 = "25"3price_input→ 100.00 = "100.00"45# Parse string to number6age→ 25 = int(age_input25)7price→ 100.0 = float(price_input100.00)89print(f"Age string: {age_input25}")10print(f"Age number: {age25}")11print(f"Age + 1 = {age25 + 1}")1213print(f"Price string: {price_input100.00}")14print(f"Price number: {price100.0}")15print(f"With tax: {price100.0 * 1.1}")1617# Complex number from string18complex_str→ 3+4j = "3+4j"19c→ (3+4j) = complex(complex_str3+4j)20print(f"Complex: {c(3+4j)}, magnitude: {abs(c)}")outputAge string: 25 Age number: 25 Age + 1 = 26 Price string: 100.00 Price number: 100.0 With tax: 110.00000000000001 Complex: (3+4j), magnitude: 5.0
See the Type Change
The conversion call changes what operations are possible. These diagrams pin the exact string inputs used in parse.py.
Number to string (format output)
Convert numbers to strings for display or formatting.
count = 42
price = 19.99
active = True
# Explicit conversion with str()
count_str = str(count)
price_str = str(price)
active_str = str(active)
print(f"Count as string: '{count_str}'")
print(f"Price as string: '{price_str}'")
print(f"Active as string: '{active_str}'")
# F-string formatting (preferred)
message = f"You have {count} items"
print(message)
# Format with specific decimal places
formatted = f"Price: ${price:.2f}"
print(formatted)
# repr() for debug representation
text = "Hello\nWorld"
print(f"str(): {str(text)}")
print(f"repr(): {repr(text)}")
count = 7
price = 19.99
active = True
# Explicit conversion with str()
count_str = str(count)
price_str = str(price)
active_str = str(active)
print(f"Count as string: '{count_str}'")
print(f"Price as string: '{price_str}'")
print(f"Active as string: '{active_str}'")
# F-string formatting (preferred)
message = f"You have {count} items"
print(message)
# Format with specific decimal places
formatted = f"Price: ${price:.2f}"
print(formatted)
# repr() for debug representation
text = "Hello\nWorld"
print(f"str(): {str(text)}")
print(f"repr(): {repr(text)}")
count = 100
price = 19.99
active = True
# Explicit conversion with str()
count_str = str(count)
price_str = str(price)
active_str = str(active)
print(f"Count as string: '{count_str}'")
print(f"Price as string: '{price_str}'")
print(f"Active as string: '{active_str}'")
# F-string formatting (preferred)
message = f"You have {count} items"
print(message)
# Format with specific decimal places
formatted = f"Price: ${price:.2f}"
print(formatted)
# repr() for debug representation
text = "Hello\nWorld"
print(f"str(): {str(text)}")
print(f"repr(): {repr(text)}")
count ← 42, price ← 19.99, active ← True, count_str ← 42, price_str ← 19.99
1count→ 42 = 42 #@count=7, 1002price→ 19.99 = 19.993active→ True = True45# Explicit conversion with str()6count_str→ 42 = str(count42)7price_str→ 19.99 = str(price19.99)8active_str→ True = str(activeTrue)910print(f"Count as string: '{count_str42}'")11print(f"Price as string: '{price_str19.99}'")12print(f"Active as string: '{active_strTrue}'")1314# F-string formatting (preferred)15message→ You have 42 items = f"You have {count42} items"16print(messageYou have 42 items)1718# Format with specific decimal places19formatted→ Price: $19.99 = f"Price: ${price19.99:.2f}"20print(formattedPrice: $19.99)2122# repr() for debug representation23text→ Hello World = "Hello\nWorld"24print(f"str(): {str(textHello World)}")25print(f"repr(): {repr(textHello World)}")outputCount as string: '42' Price as string: '19.99' Active as string: 'True' You have 42 items Price: $19.99 str(): Hello World repr(): 'Hello\nWorld'
count ← 7, price ← 19.99, active ← True, count_str ← 7, price_str ← 19.99
1count→ 7 = 72price→ 19.99 = 19.993active→ True = True45# Explicit conversion with str()6count_str→ 7 = str(count7)7price_str→ 19.99 = str(price19.99)8active_str→ True = str(activeTrue)910print(f"Count as string: '{count_str7}'")11print(f"Price as string: '{price_str19.99}'")12print(f"Active as string: '{active_strTrue}'")1314# F-string formatting (preferred)15message→ You have 7 items = f"You have {count7} items"16print(messageYou have 7 items)1718# Format with specific decimal places19formatted→ Price: $19.99 = f"Price: ${price19.99:.2f}"20print(formattedPrice: $19.99)2122# repr() for debug representation23text→ Hello World = "Hello\nWorld"24print(f"str(): {str(textHello World)}")25print(f"repr(): {repr(textHello World)}")outputCount as string: '7' Price as string: '19.99' Active as string: 'True' You have 7 items Price: $19.99 str(): Hello World repr(): 'Hello\nWorld'
count ← 100, price ← 19.99, active ← True, count_str ← 100, price_str ← 19.99
1count→ 100 = 1002price→ 19.99 = 19.993active→ True = True45# Explicit conversion with str()6count_str→ 100 = str(count100)7price_str→ 19.99 = str(price19.99)8active_str→ True = str(activeTrue)910print(f"Count as string: '{count_str100}'")11print(f"Price as string: '{price_str19.99}'")12print(f"Active as string: '{active_strTrue}'")1314# F-string formatting (preferred)15message→ You have 100 items = f"You have {count100} items"16print(messageYou have 100 items)1718# Format with specific decimal places19formatted→ Price: $19.99 = f"Price: ${price19.99:.2f}"20print(formattedPrice: $19.99)2122# repr() for debug representation23text→ Hello World = "Hello\nWorld"24print(f"str(): {str(textHello World)}")25print(f"repr(): {repr(textHello World)}")outputCount as string: '100' Price as string: '19.99' Active as string: 'True' You have 100 items Price: $19.99 str(): Hello World repr(): 'Hello\nWorld'
Use str() or f-strings for conversion with formatting options.
Truthiness conversions
Python converts values to boolean in conditions automatically.
# Falsy values in Python
print("=== Falsy Values ===")
print(f"bool(False): {bool(False)}")
print(f"bool(0): {bool(0)}")
print(f"bool(0.0): {bool(0.0)}")
print(f"bool(''): {bool('')}")
print(f"bool([]): {bool([])}")
print(f"bool(None): {bool(None)}")
# Truthy values
print("\n=== Truthy Values ===")
print(f"bool(True): {bool(True)}")
print(f"bool(1): {bool(1)}")
print(f"bool(-1): {bool(-1)}")
print(f"bool('hi'): {bool('hi')}")
print(f"bool([1, 2]): {bool([1, 2])}")
# Practical use in conditions
name = ""
if name:
print(f"Hello, {name}!")
else:
print("Name is empty")
items = []
if items:
print(f"Has {len(items)} items")
else:
print("List is empty")
# Falsy values in Python
print("=== Falsy Values ===")
print(f"bool(False): {bool(False)}")
print(f"bool(0): {bool(0)}")
print(f"bool(0.0): {bool(0.0)}")
print(f"bool(''): {bool('')}")
print(f"bool([]): {bool([])}")
print(f"bool(None): {bool(None)}")
# Truthy values
print("\n=== Truthy Values ===")
print(f"bool(True): {bool(True)}")
print(f"bool(1): {bool(1)}")
print(f"bool(-1): {bool(-1)}")
print(f"bool('hi'): {bool('hi')}")
print(f"bool([1, 2]): {bool([1, 2])}")
# Practical use in conditions
name = "Alice"
if name:
print(f"Hello, {name}!")
else:
print("Name is empty")
items = []
if items:
print(f"Has {len(items)} items")
else:
print("List is empty")
# Falsy values in Python
print("=== Falsy Values ===")
print(f"bool(False): {bool(False)}")
print(f"bool(0): {bool(0)}")
print(f"bool(0.0): {bool(0.0)}")
print(f"bool(''): {bool('')}")
print(f"bool([]): {bool([])}")
print(f"bool(None): {bool(None)}")
# Truthy values
print("\n=== Truthy Values ===")
print(f"bool(True): {bool(True)}")
print(f"bool(1): {bool(1)}")
print(f"bool(-1): {bool(-1)}")
print(f"bool('hi'): {bool('hi')}")
print(f"bool([1, 2]): {bool([1, 2])}")
# Practical use in conditions
name = "Bob"
if name:
print(f"Hello, {name}!")
else:
print("Name is empty")
items = []
if items:
print(f"Has {len(items)} items")
else:
print("List is empty")
# Falsy values in Python
print("=== Falsy Values ===")
print(f"bool(False): {bool(False)}")
print(f"bool(0): {bool(0)}")
print(f"bool(0.0): {bool(0.0)}")
print(f"bool(''): {bool('')}")
print(f"bool([]): {bool([])}")
print(f"bool(None): {bool(None)}")
# Truthy values
print("\n=== Truthy Values ===")
print(f"bool(True): {bool(True)}")
print(f"bool(1): {bool(1)}")
print(f"bool(-1): {bool(-1)}")
print(f"bool('hi'): {bool('hi')}")
print(f"bool([1, 2]): {bool([1, 2])}")
# Practical use in conditions
name = ""
if name:
print(f"Hello, {name}!")
else:
print("Name is empty")
items = [1, 2, 3]
if items:
print(f"Has {len(items)} items")
else:
print("List is empty")
name ← (empty)
1# Falsy values in Python2print("=== Falsy Values ===")3print(f"bool(False): {bool(False)}")4print(f"bool(0): {bool(0)}")5print(f"bool(0.0): {bool(0.0)}")6print(f"bool(''): {bool('')}")7print(f"bool([]): {bool([])}")8print(f"bool(None): {bool(None)}")910# Truthy values11print("\n=== Truthy Values ===")12print(f"bool(True): {bool(True)}")13print(f"bool(1): {bool(1)}")14print(f"bool(-1): {bool(-1)}")15print(f"bool('hi'): {bool('hi')}")16print(f"bool([1, 2]): {bool([1, 2])}")1718# Practical use in conditions19name→ (empty) = "" #@name="Alice", "Bob"20if name: #?truthiness_checkoutput=== Falsy Values === bool(False): False bool(0): False bool(0.0): False bool(''): False bool([]): False bool(None): False === Truthy Values === bool(True): True bool(1): True bool(-1): True bool('hi'): True bool([1, 2]): Trueelse:
20if name: #?truthiness_check21 print(f"Hello, {name}!")22else:23 print("Name is empty")outputName is emptyitems ← []
25items→ [] = [] #@items=[1, 2, 3]26if items:else:
26if items:27 print(f"Has {len(items)} items")28else:29 print("List is empty")outputList is empty
name ← Alice
1# Falsy values in Python2print("=== Falsy Values ===")3print(f"bool(False): {bool(False)}")4print(f"bool(0): {bool(0)}")5print(f"bool(0.0): {bool(0.0)}")6print(f"bool(''): {bool('')}")7print(f"bool([]): {bool([])}")8print(f"bool(None): {bool(None)}")910# Truthy values11print("\n=== Truthy Values ===")12print(f"bool(True): {bool(True)}")13print(f"bool(1): {bool(1)}")14print(f"bool(-1): {bool(-1)}")15print(f"bool('hi'): {bool('hi')}")16print(f"bool([1, 2]): {bool([1, 2])}")1718# Practical use in conditions19name→ Alice = "Alice"20if name:output=== Falsy Values === bool(False): False bool(0): False bool(0.0): False bool(''): False bool([]): False bool(None): False === Truthy Values === bool(True): True bool(1): True bool(-1): True bool('hi'): True bool([1, 2]): Trueif name:
19name = "Alice"20if nameAlice:21 print(f"Hello, {nameAlice}!")22else:outputHello, Alice!items ← []
25items→ [] = []26if items:else:
26if items:27 print(f"Has {len(items)} items")28else:29 print("List is empty")outputList is empty
name ← Bob
1# Falsy values in Python2print("=== Falsy Values ===")3print(f"bool(False): {bool(False)}")4print(f"bool(0): {bool(0)}")5print(f"bool(0.0): {bool(0.0)}")6print(f"bool(''): {bool('')}")7print(f"bool([]): {bool([])}")8print(f"bool(None): {bool(None)}")910# Truthy values11print("\n=== Truthy Values ===")12print(f"bool(True): {bool(True)}")13print(f"bool(1): {bool(1)}")14print(f"bool(-1): {bool(-1)}")15print(f"bool('hi'): {bool('hi')}")16print(f"bool([1, 2]): {bool([1, 2])}")1718# Practical use in conditions19name→ Bob = "Bob"20if name:output=== Falsy Values === bool(False): False bool(0): False bool(0.0): False bool(''): False bool([]): False bool(None): False === Truthy Values === bool(True): True bool(1): True bool(-1): True bool('hi'): True bool([1, 2]): Trueif name:
19name = "Bob"20if nameBob:21 print(f"Hello, {nameBob}!")22else:outputHello, Bob!items ← []
25items→ [] = []26if items:else:
26if items:27 print(f"Has {len(items)} items")28else:29 print("List is empty")outputList is empty
name ← (empty)
1# Falsy values in Python2print("=== Falsy Values ===")3print(f"bool(False): {bool(False)}")4print(f"bool(0): {bool(0)}")5print(f"bool(0.0): {bool(0.0)}")6print(f"bool(''): {bool('')}")7print(f"bool([]): {bool([])}")8print(f"bool(None): {bool(None)}")910# Truthy values11print("\n=== Truthy Values ===")12print(f"bool(True): {bool(True)}")13print(f"bool(1): {bool(1)}")14print(f"bool(-1): {bool(-1)}")15print(f"bool('hi'): {bool('hi')}")16print(f"bool([1, 2]): {bool([1, 2])}")1718# Practical use in conditions19name→ (empty) = ""20if name:output=== Falsy Values === bool(False): False bool(0): False bool(0.0): False bool(''): False bool([]): False bool(None): False === Truthy Values === bool(True): True bool(1): True bool(-1): True bool('hi'): True bool([1, 2]): Trueelse:
20if name:21 print(f"Hello, {name}!")22else:23 print("Name is empty")outputName is emptyitems ← [1, 2, 3]
25items→ [1, 2, 3] = [1, 2, 3]26if items:if items:
25items = [1, 2, 3]26if items[1, 2, 3]:27 print(f"Has {len(items[1, 2, 3])} items")28else:outputHas 3 items
Exercise: parse_errors.py
Handle invalid input: what happens with ValueError?