Curriculum
Python provides the flexibility to convert data from one type to another. This process is called type conversion or type casting. Understanding type conversion is essential because data in real-world applications often comes in different forms (e.g., user input is typically received as a string and may need to be converted into an integer for mathematical operations).
This section covers:
int()
, float()
, str()
, and bool()
)By the end of this lesson, you will be able to convert between different data types and avoid common conversion errors.
Python automatically converts one data type into another when necessary, which is known as implicit conversion. This typically happens when performing operations involving mixed data types.
num_int = 10 # Integer
num_float = 2.5 # Float
result = num_int + num_float
print(result) # Output: 12.5
print(type(result)) # Output: <class 'float'>
Python automatically converts the integer 10
into a float (10.0
) before performing the addition, ensuring that the result is also a float.
num = 0
print(bool(num)) # Output: False
num = 5
print(bool(num)) # Output: True
In Python, 0 is considered False
, while any nonzero number is considered True
when converted to a Boolean.
Explicit type conversion (also known as type casting) is when the programmer manually converts one data type into another using built-in functions.
Function | Description | Example |
---|---|---|
int(x) |
Converts x to an integer |
int("10") → 10 |
float(x) |
Converts x to a float |
float("3.14") → 3.14 |
str(x) |
Converts x to a string |
str(100) → "100" |
bool(x) |
Converts x to a Boolean |
bool(0) → False, bool(5) → True |
Strings that contain numeric values can be converted into integers or floats.
num_str = "25" # This is a string
num_int = int(num_str) # Convert to integer
print(num_int) # Output: 25
print(type(num_int)) # Output: <class 'int'>
If a string contains only numeric characters, int()
will successfully convert it into an integer.
num_str = "12.34"
num_float = float(num_str) # Convert to float
print(num_float) # Output: 12.34
print(type(num_float)) # Output: <class 'float'>
A string containing decimal values can be converted into a float using float()
.
If a string contains non-numeric characters, attempting to convert it to an integer or float will result in an error.
num_str = "hello"
num_int = int(num_str) # This will raise an error
Error Output:
ValueError: invalid literal for int() with base 10: 'hello'
To prevent this, always validate or check the input before conversion.
When you need to concatenate numbers with strings, you must convert them to strings first.
age = 25
message = "I am " + str(age) + " years old."
print(message) # Output: I am 25 years old.
pi = 3.14159
print("The value of pi is " + str(pi))
Without str()
, Python would raise a TypeError because it does not allow string concatenation with numbers.
print(bool(0)) # Output: False
print(bool(1)) # Output: True
print(bool(-5)) # Output: True
Any nonzero number is treated as True, while 0
is treated as False.
print(bool("")) # Output: False (empty string)
print(bool("Hello")) # Output: True
An empty string evaluates to False
, while any non-empty string evaluates to True
.
print(bool([])) # Output: False (empty list)
print(bool([1, 2, 3])) # Output: True
An empty list evaluates to False
, while a non-empty list evaluates to True
.
Type conversion is frequently used in real-world applications, such as:
age = input("Enter your age: ") # Always returns a string
age = int(age) # Convert to integer
print("Next year, you will be", age + 1)
data = "45.6"
temperature = float(data) # Convert to float
price = 19.99
discount_price = int(price) # Convert float to integer
This section has discussed the following concepts:
int
to float
).int()
, float()
, str()
, and bool()
.Understanding type conversion helps prevent errors and allows data manipulation in real-world applications.
In the next lesson, 2.5 Input and Output in Python, you will learn how to take user input and display output using formatted text.
Not a member yet? Register now
Are you a member? Login now