In Python, while variables can hold different types of data, the type matters when you perform operations. You can't directly perform mathematical addition between a number and a string representation of a number, like 42 + "10"
. Python treats "10"
as text, not the numerical value ten. To make this work, you need to explicitly tell Python to treat "10"
as a number. This process of changing a value's data type is known as type conversion or type casting.
Python provides built-in functions to handle common type conversions. Think of them as tools to reshape your data into the format you need for a particular task. The main functions for converting between the basic types we've discussed are:
int()
: Converts a value to an integer (whole number).float()
: Converts a value to a floating-point number (number with a decimal).str()
: Converts a value to a string (text).bool()
: Converts a value to a boolean (True
or False
).Let's look at how each one works.
int()
The int()
function attempts to create an integer from its input.
From Floats: When converting a float to an integer, Python truncates the decimal part, essentially cutting it off. It does not round to the nearest whole number.
count_float = 9.8
count_int = int(count_float)
print(count_int) # Output: 9
price_float = 15.2
price_int = int(price_float)
print(price_int) # Output: 15
From Strings: You can convert strings that contain only digits into integers.
num_string = "101"
num_int = int(num_string)
print(num_int * 2) # Output: 202
Potential Errors: If you try to convert a string that cannot be interpreted as a whole number (like text or a number with a decimal point), Python will raise a ValueError
.
# This will cause an error:
# value_error_int = int("hello")
# ValueError: invalid literal for int() with base 10: 'hello'
# This will also cause an error:
# value_error_float_string = int("3.14")
# ValueError: invalid literal for int() with base 10: '3.14'
Handling such errors is something we'll cover later in the course. For now, be aware that conversion isn't always possible.
float()
The float()
function converts values into floating-point numbers.
From Integers: Converting an integer to a float simply adds a decimal part (.0
).
whole_number = 50
float_number = float(whole_number)
print(float_number) # Output: 50.0
From Strings: You can convert strings that represent either whole numbers or numbers with decimals.
pi_string = "3.14159"
pi_float = float(pi_string)
print(pi_float) # Output: 3.14159
count_string = "100"
count_float_from_string = float(count_string)
print(count_float_from_string) # Output: 100.0
Potential Errors: Similar to int()
, trying to convert a string that doesn't represent a valid number will result in a ValueError
.
# This will cause an error:
# value_error_float = float("not a number")
# ValueError: could not convert string to float: 'not a number'
str()
The str()
function converts its argument into a string representation. This is extremely useful for creating output messages that combine text with the values of variables.
From Numbers: Integers and floats can easily be turned into strings.
item_count = 5
message = "You have " + str(item_count) + " items in your cart."
print(message) # Output: You have 5 items in your cart.
temperature = 22.5
weather_report = "The temperature is " + str(temperature) + " degrees Celsius."
print(weather_report) # Output: The temperature is 22.5 degrees Celsius.
Without str()
, trying to concatenate a string and a number directly (e.g., "Value: " + 5
) would cause a TypeError
.
From Booleans: Boolean values are converted to the strings "True"
or "False"
.
is_active = True
status_message = "User active status: " + str(is_active)
print(status_message) # Output: User active status: True
Almost any Python object can be converted to some kind of string representation using str()
, making it a very versatile function.
bool()
The bool()
function converts a value to its boolean equivalent (True
or False
). Python has a concept of "truthiness" where certain values are considered inherently false in a boolean context, while most others are considered true.
Values considered False
:
0
0.0
None
(which represents the absence of a value)""
, empty list []
, empty tuple ()
){}
)Values considered True
:
1
, -10
, 0.5
)"hello"
, " "
, "False"
)[1]
, (None,)
, {'a': 1}
)Here are some examples:
print(bool(100)) # Output: True
print(bool(-5.5)) # Output: True
print(bool("Python")) # Output: True
print(bool([1, 2, 3])) # Output: True
print(bool(0)) # Output: False
print(bool(0.0)) # Output: False
print(bool("")) # Output: False
print(bool([])) # Output: False
print(bool({})) # Output: False
print(bool(None)) # Output: False
Understanding truthiness is important when we start using conditional statements (if
/else
) to control program flow based on whether a condition is true or false.
Type conversion is immediately relevant because of how Python handles input from users. When you use the input()
function (which we'll cover next) to get data from the keyboard, it always returns that data as a string, regardless of what the user types.
If you ask the user for their age and they type 30
, the input()
function will give you the string "30"
, not the integer 30
. If you then want to perform calculations, like finding out their age in five years, you'll need to convert that string "30"
into an integer 30
using int()
before you can add 5
to it.
Being able to explicitly convert between types using int()
, float()
, str()
, and bool()
is a fundamental skill that allows you to manipulate data correctly and avoid type-related errors in your programs.
© 2025 ApX Machine Learning