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.
int_to_float.py
a =
b =
# 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 =
b =
# 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 =
b =
# 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 =
b =
# 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 =
b =
# 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 =
b =
# 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 =
b =
# 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 =
b =
# 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 =
b =
# 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}%")
Python 3's / operator always returns float. Use // for integer division.
Float to int (truncation)
Sometimes you need a whole number from a decimal.
float_to_int.py
price =
# 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 =
# 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 =
# 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}")
int()
Convert to integer: `int("42")` → `42`, `int(3.7)` → `3` (truncates, doesn't round)
String to number (parse input)
User input is text. Convert to numbers for calculation.
parse.py
# Simulated user input
age_input =
price_input =
# 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 =
price_input =
# 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 =
price_input =
# 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 =
price_input =
# 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 =
price_input =
# 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 =
price_input =
# 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 =
price_input =
# 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 =
price_input =
# 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 =
price_input =
# 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)}")
float()
Convert to float: `float("3.14")` → `3.14`, `float(5)` → `5.0`
Number to string (format output)
Convert numbers to strings for display or formatting.
to_string.py
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)}")
Use str() or f-strings for conversion with formatting options.
str()
Convert to string: `str(42)` → `"42"`
Truthiness conversions
Python converts values to boolean in conditions automatically.
truthiness.py
# 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 =
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 =
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 =
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 =
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 =
if items:
print(f"Has {len(items)} items")
else:
print("List is empty")
bool()
Convert to boolean: `bool(0)` → `False`, `bool(1)` → `True`
truthy/falsy
Falsy: `False`, `0`, `""`, `[]`, `None`. Everything else is truthy.
Exercise: parse_errors.py
Handle invalid input: what happens with ValueError?