Type conversion
In Python, data is stored in specific data types, such as numbers and text. Sometimes, you may need to convert data from one type to another.
This process, called type conversion or type casting, is crucial for ensuring that different types of data work together seamlessly in your programs.
Common type conversion functions
Converting to an Integer int()
int()
The int()
- Floats (decimal numbers).
- Strings containing numbers (e.g.,
"42"
).
Examples:
# From float to integer
score = int(9.7) # score becomes 9
# From string to integer
count = int("42") # count becomes 42
Usage:
- When converting a float,
truncates the decimal part (it does not round).int()
- It raises an error if the string cannot be interpreted as a number (e.g.,
).int("abc")
Converting to a Float float()
float()
The float()
- Integers.
- Strings containing numbers.
Examples:
# From integer to float
age = float(30) # age becomes 30.0
# From string to float
price = float("19.99") # price becomes 19.99
Usage:
- Floats are ideal for calculations requiring precision, such as measurements or monetary values.
Converting to a String str()
str()
The str()
- Numbers (integers or floats).
- Booleans.
Examples:
# From integer to string
age_text = str(25) # age_text becomes "25"
# From float to string
pi_text = str(3.14159) # pi_text becomes "3.14159"
Usage:
- Use
to display data as text, such as including a number in a message or creating formatted output.str()
Converting to a Boolean bool()
bool()
The bool()
True
False
Basic Rules:
- Zero values (e.g.,
0
,0.0
,""
) become .False
- Non-zero values or non-empty strings (e.g.,
"Hello"
,42
) become .True
Examples:
# From integer to boolean
is_active = bool(1) # is_active becomes True
# From string to boolean
has_name = bool("Alice") # has_name becomes True
Usage:
- Booleans are essential for decision-making and controlling the flow of your program.
Type conversion in action
Type conversion is useful in a variety of scenarios, such as processing user input or combining data types in calculations.
Example 1: Converting user input
User input in Python is always a string. You may need to convert it to another type for calculations:
user_age = input("Enter your age: ") # e.g., "25"
user_age = int(user_age) # Convert to an integer
print("You will be", user_age + 1, "next year!")
Example 2: Combining a number with text
When concatenating numbers with strings, you must first convert the number to a string:
pi = 3.14159
message = "The value of pi is " + str(pi) # Convert pi to string
print(message) # Output: The value of pi is 3.14159
Example 3: Calculating with different types
To perform calculations, ensure all values are of compatible types:
length = "5.5" # String
width = 2 # Integer
area = float(length) * width # Convert length to float
print("The area is:", area) # Output: The area is: 11.0
Why is type conversion important?
Type conversion allows for:
- Flexibility: Ensures different data types work together.
- Error Prevention: Avoids type-related errors during calculations or operations.
- Enhanced Functionality: Converts data for specific tasks, such as displaying numbers as text or performing arithmetic.
Conclusion
Type conversion is a fundamental skill for working with diverse data in Python. Whether you're converting a user’s input to a number for calculations or formatting output for display, these functions keep your code versatile and efficient.
Start practicing with int()
float()
str()
bool()