Casting in Python refers to converting a variable from one data type to another. Python provides built-in functions for casting to ensure the correct data type is used in operations or calculations.
Why Use Casting?
- To perform operations that require specific data types.
- To ensure consistency in data types within a program.
- To handle data input from users, which is often read as a string.
Types of Casting in Python
1. Implicit Casting
Python automatically converts one data type to another when it is safe to do so. This is known as type coercion.
2. Explicit Casting
Explicit casting requires you to use specific functions to convert data types.
Explicit Casting Functions
1. int()
Converts a value to an integer.
- Floats are truncated (decimal part removed).
- Strings must represent a valid integer; otherwise, an error occurs.
Example:
x = 5.7
y = "10"
# Float to Integer
result1 = int(x) # Converts 5.7 to 5
# String to Integer
result2 = int(y) # Converts "10" to 10
print(result1, result2)
2. float()
Converts a value to a floating-point number.
- Integers become floats.
- Strings must represent valid numbers.
Example:
x = 10
y = "3.14"
# Integer to Float
result1 = float(x) # Converts 10 to 10.0
# String to Float
result2 = float(y) # Converts "3.14" to 3.14
print(result1, result2)
3. str()
Converts a value to a string.
- Works with numbers, booleans, and more.
Example:
x = 42
y = True
# Number to String
result1 = str(x) # Converts 42 to "42"
# Boolean to String
result2 = str(y) # Converts True to "True"
print(result1, result2)
4. bool()
Converts a value to a boolean.
- Zero, empty strings, empty collections, and
None
areFalse
. - Non-zero numbers and non-empty values are
True
.
Example:
x = 0
y = "Infovistar Python"
# Integer to Boolean
result1 = bool(x) # Converts 0 to False
# String to Boolean
result2 = bool(y) # Converts "Infovistar Python" to True
print(result1, result2)
Implicit Casting
Python automatically performs safe type conversions.
Example:
x = 10 # Integer
y = 3.5 # Float
# Implicit Conversion
result = x + y # Converts x to a float, so result is 13.5
print(result)
Common Casting Errors
1. Invalid Strings: Converting non-numeric strings to int()
or float()
will raise a ValueError
.
x = "hello"
# int(x) # Raises ValueError
2. Non-Iterable to list(): Trying to convert a non-iterable value to a list raises a TypeError
.
x = 42
# list(x) # Raises TypeError