🔄 Converting Types
Type conversion is the process of changing data from one type to another. This is essential when working with user input, data from files, or when you need to perform operations that require specific data types. Python provides built-in functions to convert between different types safely and efficiently.
Understanding type conversion helps you handle data from various sources and ensures your operations work correctly with the right data types.
# Basic type conversion examples
text_number = "42"
number = int(text_number)
decimal = float(text_number)
back_to_text = str(number)
print(f"Original: {text_number} (type: {type(text_number).__name__})")
print(f"As integer: {number} (type: {type(number).__name__})")
print(f"As float: {decimal} (type: {type(decimal).__name__})")
print(f"Back to string: {back_to_text} (type: {type(back_to_text).__name__})")
📝 Converting to Strings
The str()
function converts any value to a string representation. This is the most universal conversion function - it works with virtually any Python object and never fails.
# Converting different types to strings
number = 123
decimal = 45.67
boolean = True
none_value = None
my_list = [1, 2, 3]
print(f"Number to string: '{str(number)}'")
print(f"Decimal to string: '{str(decimal)}'")
print(f"Boolean to string: '{str(boolean)}'")
print(f"None to string: '{str(none_value)}'")
print(f"List to string: '{str(my_list)}'")
🔢 Converting to Numbers
Python provides int()
and float()
functions to convert values to numbers. These conversions are crucial when working with user input or data from external sources.
String to Number Conversion
# Converting to numbers
text_integer = "123"
text_decimal = "45.67"
boolean_true = True
boolean_false = False
print(f"String to int: {int(text_integer)}") # 123
print(f"String to float: {float(text_decimal)}") # 45.67
print(f"Boolean True to int: {int(boolean_true)}") # 1
print(f"Boolean False to int: {int(boolean_false)}")# 0
print(f"Float to int: {int(45.67)}") # 45 (truncated!)
🔄 Quick Conversion Practice
Let's practice converting between different data types using Python's built-in functions!
Hands-on Exercise
Practice converting between strings, numbers, and booleans using int(), float(), str(), and bool() functions.
# Type Conversion Practice - Simple and focused!
# Convert these strings to numbers
age_text = "25"
price_text = "19.99"
age_number = # TODO: Your code here (convert to integer)
price_number = # TODO: Your code here (convert to float)
# Convert these numbers to strings
score = 95
temperature = 72.5
score_text = # TODO: Your code here (convert to string)
temp_text = # TODO: Your code here (convert to string)
# Convert these to booleans
empty_string = ""
zero_number = 0
some_text = "hello"
is_empty = # TODO: Your code here (convert empty string to bool)
is_zero = # TODO: Your code here (convert zero to bool)
has_text = # TODO: Your code here (convert "hello" to bool)
print(f"Age: {age_number} (type: {type(age_number).__name__})")
print(f"Price: {price_number} (type: {type(price_number).__name__})")
print(f"Score as text: '{score_text}'")
print(f"Temperature as text: '{temp_text}'")
print(f"Empty string is: {is_empty}")
print(f"Zero is: {is_zero}")
print(f"'hello' is: {has_text}")
Solution and Explanation 💡
Click to see the complete solution
# Type Conversion Practice - Simple solution
# Convert these strings to numbers
age_text = "25"
price_text = "19.99"
age_number = int(age_text) # Convert string to integer
price_number = float(price_text) # Convert string to float
# Convert these numbers to strings
score = 95
temperature = 72.5
score_text = str(score) # Convert integer to string
temp_text = str(temperature) # Convert float to string
# Convert these to booleans
empty_string = ""
zero_number = 0
some_text = "hello"
is_empty = bool(empty_string) # Empty string → False
is_zero = bool(zero_number) # Zero → False
has_text = bool(some_text) # Non-empty string → True
print(f"Age: {age_number} (type: {type(age_number).__name__})")
print(f"Price: {price_number} (type: {type(price_number).__name__})")
print(f"Score as text: '{score_text}'")
print(f"Temperature as text: '{temp_text}'")
print(f"Empty string is: {is_empty}")
print(f"Zero is: {is_zero}")
print(f"'hello' is: {has_text}")
Key Learning Points:
- 📌 int(): Converts strings to whole numbers
- 📌 float(): Converts strings to decimal numbers
- 📌 str(): Converts any value to text (always works!)
- 📌 bool(): Empty/zero values become False, others become True
✅❌ Converting to Booleans
The bool()
function converts any value to a boolean following Python's truthiness rules. Only specific "empty" or "zero" values become False
.
# Converting to booleans
print(f"Empty string: {bool('')}") # False
print(f"Non-empty string: {bool('hello')}") # True
print(f"String 'False': {bool('False')}") # True (surprising!)
print(f"Zero: {bool(0)}") # False
print(f"Non-zero number: {bool(42)}") # True
print(f"Empty list: {bool([])}") # False
print(f"Non-empty list: {bool([1, 2, 3])}") # True
Essential Conversion Functions 🛠️
Python provides comprehensive functions for converting between different data types:
Function | Purpose | Example | Result |
---|---|---|---|
str(x) | Convert to string | str(123) | "123" |
int(x) | Convert to integer | int("42") | 42 |
float(x) | Convert to float | float("3.14") | 3.14 |
bool(x) | Convert to boolean | bool("hello") | True |
list(x) | Convert to list | list("abc") | ['a', 'b', 'c'] |
tuple(x) | Convert to tuple | tuple([1, 2, 3]) | (1, 2, 3) |
set(x) | Convert to set | set([1, 2, 2, 3]) | {1, 2, 3} |
⚠️ Handling Conversion Errors
Not all conversions are possible. When converting strings to numbers, the string must contain valid numeric data, or Python raises a ValueError
.
Safe Conversion Examples
# Safe conversion techniques
valid_number = "123"
invalid_number = "hello"
# This works
result1 = int(valid_number)
print(f"Converted '{valid_number}': {result1}")
# Safe conversion with error handling
def safe_int_conversion(value):
try:
return int(value)
except ValueError:
print(f"Cannot convert '{value}' to integer")
return None
result2 = safe_int_conversion(invalid_number)
result3 = safe_int_conversion("456")
print(f"Safe conversion results: {result2}, {result3}")
🔄 Implicit vs Explicit Conversion
Python sometimes converts types automatically (implicit) and sometimes requires you to convert explicitly.
Automatic vs Manual Conversion
# Implicit conversion (automatic)
result1 = 5 + 2.5 # int + float = float automatically
print(f"5 + 2.5 = {result1} (type: {type(result1).__name__})")
# Explicit conversion (manual)
number = 42
text = "The answer is " + str(number) # Must convert manually
print(text)
# This would cause an error:
# bad_text = "The answer is " + number # TypeError!
💬 Working with User Input
User input always comes as strings in Python. Converting user input to appropriate types is essential for mathematical operations and proper data handling.
# Simulating user input processing
user_inputs = ["25", "3.14", "True", ""]
print("Processing user input:")
for i, user_input in enumerate(user_inputs):
print(f"\nInput {i+1}: '{user_input}'")
# Convert to different types
if user_input.isdigit():
as_int = int(user_input)
print(f" As integer: {as_int}")
try:
as_float = float(user_input)
print(f" As float: {as_float}")
except ValueError:
print(f" Cannot convert to float")
as_bool = bool(user_input)
print(f" As boolean: {as_bool}")
🎯 Key Takeaways
🧠 Test Your Knowledge
🚀 What's Next?
Now that you understand Python's basic data types and type conversion, you're ready to explore operators - the tools that let you perform operations on your data and create more complex expressions.
Learn about Python Operators to start working with mathematical and logical operations, or explore Math Operations for specific mathematical calculations.
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.