
Python
Type conversion is the process of changing data from one type to another. Sometimes you need to convert a string to a number for calculations, or a number to a string for display. Python provides built-in functions like int(), float(), str(), and bool() to convert between types. Understanding type conversion is essential for combining different data sources and handling user input.
Python provides four main conversion functions for the basic data types. int() converts to integer, float() to decimal, str() to string, and bool() to boolean. Each function takes a value and returns the converted version, or raises an error if the conversion isn't possible.
# String to Integer
age_string = "25"
age_number = int(age_string) # 25
print(f"Type: {type(age_number)}") # <class 'int'>
# String to Float
price_string = "19.99"
price_float = float(price_string) # 19.99
print(f"Type: {type(price_float)}") # <class 'float'>
# Number to String
count = 42
count_string = str(count) # "42"
print(f"Type: {type(count_string)}") # <class 'str'>
# Integer to Float
number = 10
decimal = float(number) # 10.0
print(f"Type: {type(decimal)}") # <class 'float'>Converting strings to numbers is one of the most common operations, especially when processing user input. int() and float() can convert strings that contain valid numbers. If the string doesn't contain a valid number, Python raises an error, so you need to be careful with untrusted input.
# String to integer
num_str = "100"
num_int = int(num_str) # 100
# String to float
decimal_str = "3.14"
decimal_float = float(decimal_str) # 3.14
# From other numbers
int_to_float = float(42) # 42.0
float_to_int = int(3.99) # 3 (truncates, doesn't round)
# Conversion with different bases (advanced)
binary = "1010"
decimal = int(binary, 2) # 10
print(f"String '100' as int: {num_int}")
print(f"String '3.14' as float: {decimal_float}")
print(f"Float to int truncates: {float_to_int}")Converting to string is essential for displaying numbers in messages or concatenating them with other text. The str() function converts any data type to its string representation. This is simpler than integer or float conversion because almost any value can be converted to a string.
# Numbers to strings
age = 25
price = 19.99
count = 0
age_str = str(age) # "25"
price_str = str(price) # "19.99"
count_str = str(count) # "0"
# Combining with other text
message = f"I am {str(age)} years old"
# Booleans to strings
is_admin = True
admin_str = str(is_admin) # "True"
print(f"Age as string: '{age_str}'")
print(message)
print(f"Admin: {admin_str}")Converting to boolean is less common but useful for creating flags from other values. Any non-zero number converts to True, zero converts to False. Non-empty strings convert to True, empty strings to False. This is used when you need a boolean decision based on data.
# Numbers to boolean
bool(1) # True (non-zero)
bool(0) # False (zero)
bool(3.14) # True (non-zero)
bool(-5) # True (non-zero)
# Strings to boolean
bool("hello") # True (non-empty string)
bool("") # False (empty string)
bool("False") # True (non-empty, even though it says "False"!)
# Practical example
user_input = "yes"
is_valid = bool(user_input) # True (non-empty string)Not all conversions are possible, and Python will raise an error if you try to convert invalid data. A string that doesn't contain a number can't be converted to int or float. Understanding what conversions work helps you avoid these errors.
# These work
int("100") # 100
float("3.14") # 3.14
str(42) # "42"
# These fail (errors)
# int("hello") # ValueError: invalid literal
# float("abc") # ValueError: could not convert string to float
# int("3.14") # ValueError: invalid literal (has decimal)
# Safe conversion with defaults
def safe_int(value, default=0):
try:
return int(value)
except ValueError:
return default
result = safe_int("hello", 0) # Returns 0 (default)
print(result)# Get input as string, convert to integer
birth_year_str = "2000"
birth_year = int(birth_year_str)
current_year = 2024
age = current_year - birth_year
print(f"Born in {birth_year}, you are {age} years old")# Convert numbers to strings for display
item_price = 12.50
quantity = 3
total = item_price * quantity
print(f"Item: ${str(item_price)}")
print(f"Quantity: {quantity}")
print(f"Total: ${str(total)}")# Convert string input to boolean-like behavior
feature_enabled = "1"
is_on = bool(int(feature_enabled))
if is_on:
print("Feature is enabled")
else:
print("Feature is disabled")| Function | Converts To | Example | Result |
|---|---|---|---|
| int() | Integer | int("42") | 42 |
| float() | Float | float("3.14") | 3.14 |
| str() | String | str(42) | "42" |
| bool() | Boolean | bool(1) | True |
| int() | From Float | int(3.99) | 3 |
| float() | From Int | float(42) | 42.0 |
You can convert between types, but how do you get data from the user? Let's learn about getting user input!
Ready to practice? Try challenges or take the quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward