- Understand implicit vs explicit type conversion
- Convert between integers, floats, strings, and booleans
- Handle user input correctly with type conversion
- Avoid common type conversion errors
Type Conversion
Imagine you're at an international airport. The currency exchange booth converts your dollars to euros, your euros to yen, and so on. Each currency represents the same value, just in a different form. Type conversion in Python works the same way – it transforms data from one type to another while preserving its meaning.
Sometimes Python does this automatically (like when adding an integer and a float). Other times, you need to explicitly tell Python to make the conversion. Understanding when and how to convert types is essential for writing programs that handle real-world data.
Two Types of Conversion
Type Conversion Types
IMPLICIT (Automatic)
Python does it for you, silently
Example: 5 + 2.0 → 7.0 (int + float = float)
EXPLICIT (Manual)
You tell Python to convert using functions
Example: int("42") → 42 (string to int)
Implicit Conversion (Type Coercion)
Python automatically converts types when it makes sense and no data is lost.
The Widening Rule
Python converts "smaller" types to "larger" types to preserve precision:
int → float → complex
When mixing types, Python chooses the more "capable" type.
Examples of Implicit Conversion
# Integer + Float = Float
result = 5 + 2.5
print(result) # 7.5
print(type(result)) # <class 'float'>
# Integer * Float = Float
result = 3 * 4.0
print(result) # 12.0
# Boolean + Integer = Integer (True = 1, False = 0)
result = True + 10
print(result) # 11
Why Floats Win
Think about it: if you add 5 + 2.5, the result 7.5 can only be represented as a float. If Python converted to int, you'd lose the .5!
# Python preserves precision
total = 100 + 0.99 # 100.99 (float)
# If Python used int: 100 (loses .99!)
When Implicit Conversion Doesn't Work
# Python won't automatically convert incompatible types
# text = "Age: " + 25 # TypeError!
# You must be explicit
text = "Age: " + str(25) # "Age: 25"
Explicit Conversion Functions
When automatic conversion isn't possible or desired, use these built-in functions:
Conversion Functions
int() Convert to integer
float() Convert to floating-point number
str() Convert to string
bool() Convert to boolean
Converting to Integers: int()
The int() function converts values to whole numbers.
From Float to Int
# int() TRUNCATES (cuts off decimals), it doesn't round!
print(int(3.9)) # 3 (not 4!)
print(int(3.1)) # 3
print(int(-3.9)) # -3 (towards zero)
print(int(-3.1)) # -3
# If you want rounding, use round() first
print(round(3.9)) # 4
print(int(round(3.9))) # 4
Important:
int()truncates toward zero, it doesn't round!
From String to Int
# Works with numeric strings
age = int("25")
print(age) # 25
print(type(age)) # <class 'int'>
# Works with negative numbers
temperature = int("-5")
print(temperature) # -5
# Spaces are handled
score = int(" 100 ") # Works! → 100
What Doesn't Work
# Decimal strings
# int("3.14") # ValueError! Use float() first
# Non-numeric strings
# int("hello") # ValueError!
# Empty strings
# int("") # ValueError!
# Solution for decimal strings
value = int(float("3.14")) # 3
Real-World Example
# User age input (input() always returns string!)
age_input = "25" # Simulating user input
age = int(age_input)
# Now we can do math
years_until_30 = 30 - age # 5
Converting to Floats: float()
The float() function creates decimal numbers.
From Int to Float
whole_number = 42
decimal_number = float(whole_number)
print(decimal_number) # 42.0
From String to Float
# Works with decimal strings
price = float("19.99")
print(price) # 19.99
# Also works with integers in string form
value = float("100")
print(value) # 100.0
# Scientific notation works too!
big = float("1e6") # 1000000.0
small = float("1e-3") # 0.001
What Doesn't Work
# Non-numeric strings
# float("hello") # ValueError!
# Multiple decimals
# float("3.14.15") # ValueError!
Converting to Strings: str()
The str() function converts anything to text. It's the most flexible converter!
Everything Can Become a String
# Numbers to strings
print(str(42)) # "42"
print(str(3.14)) # "3.14"
print(str(-17)) # "-17"
# Booleans to strings
print(str(True)) # "True"
print(str(False)) # "False"
# None to string
print(str(None)) # "None"
Why Convert to String?
Building messages:
name = "Alice"
age = 25
message = "Hello, " + name + "! You are " + str(age) + " years old."
# "Hello, Alice! You are 25 years old."
Better way with f-strings:
message = f"Hello, {name}! You are {age} years old."
# F-strings handle conversion automatically!
Display Formatting
price = 19.99
quantity = 3
total = price * quantity
# Without str()
# print("Total: $" + total) # TypeError!
# With str()
print("Total: $" + str(total)) # "Total: $59.97"
# Better: f-string
print(f"Total: ${total}") # "Total: $59.97"
Converting to Booleans: bool()
The bool() function reveals Python's concept of "truthy" and "falsy" values.
The Falsy Values
These convert to False:
# The "Falsy" club - all convert to False
print(bool(0)) # False - zero
print(bool(0.0)) # False - zero float
print(bool("")) # False - empty string
print(bool([])) # False - empty list
print(bool(None)) # False - None
print(bool({})) # False - empty dict
The Truthy Values
Everything else is True:
# All "Truthy" - convert to True
print(bool(1)) # True - any non-zero number
print(bool(-5)) # True - negative counts too!
print(bool(0.001)) # True - any non-zero float
print(bool("hello")) # True - non-empty string
print(bool(" ")) # True - even just a space!
print(bool([1, 2])) # True - non-empty list
Memory Aid: The Falsy Six
The Six Falsy Values (Everything Else is Truthy)
0 Zero integer
0.0 Zero float
"" Empty string
[] Empty list
{} Empty dictionary
None The None value
Practical Use
# Check if a list has items
items = ["apple", "banana"]
if bool(items): # Or simply: if items:
print("You have items!")
# Check if username was entered
username = ""
if not bool(username): # Or: if not username:
print("Please enter a username")
Handling User Input
Here's where type conversion becomes essential: input() ALWAYS returns a string!
The Classic Mistake
# User types "25"
age = input("Enter your age: ") # age is "25" (string!)
# This won't work as expected!
# new_age = age + 1 # TypeError: can't add str and int
The Solution
# Always convert input when you need numbers
age = int(input("Enter your age: "))
new_age = age + 1 # Works!
# For decimal numbers
price = float(input("Enter price: "))
tax = price * 0.08 # Works!
Safe Input Handling
What if the user types "hello" when you expect a number?
# Basic safe input (we'll learn try/except later!)
user_input = input("Enter a number: ")
# Check if it looks like a number
if user_input.isdigit():
number = int(user_input)
print(f"Your number doubled: {number * 2}")
else:
print("That's not a valid number!")
Conversion Reference Table
| From → To | int() | float() | str() | bool() |
|---|---|---|---|---|
| int | — | float(42) → 42.0 |
str(42) → "42" |
bool(42) → True |
| float | int(3.7) → 3 |
— | str(3.14) → "3.14" |
bool(3.14) → True |
| str | int("42") → 42 |
float("3.14") → 3.14 |
— | bool("hi") → True |
| bool | int(True) → 1 |
float(True) → 1.0 |
str(True) → "True" |
— |
Practical Example: Simple Calculator
# A simple calculator using type conversion
print("=" * 30)
print(" SIMPLE CALCULATOR")
print("=" * 30)
# Get user input (strings)
num1_str = "15" # Simulating input
num2_str = "4" # Simulating input
operation = "+" # Simulating input
# Convert to numbers
num1 = float(num1_str)
num2 = float(num2_str)
# Perform calculation
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
result = num1 / num2 if num2 != 0 else "Error: Division by zero"
# Display result (convert back to string for nice formatting)
print(f"\n{num1} {operation} {num2} = {result}")
print("=" * 30)
Key Takeaways
Remember These Points
IMPLICIT: Python converts automatically when safe
• int + float → float
• Won't mix incompatible types (str + int)
EXPLICIT: Use conversion functions
• int() - converts to integer (truncates floats!)
• float() - converts to decimal number
• str() - converts anything to text
• bool() - converts to True/False
WATCH OUT FOR:
• int("3.14") fails! Use float() first
• int("hello") fails! Not all strings are numbers
• input() ALWAYS returns a string
FALSY VALUES: 0, 0.0, "", [], {}, None
What's Next?
Congratulations on completing the Python Basics module! You now understand variables, data types, operators, and type conversion – the fundamental building blocks of Python programming.
In the next module, we'll explore Control Flow – learning how to make decisions with if statements and repeat actions with loops. Get ready to make your programs smarter!
