In Python, casting refers to converting one data type into another. Python provides several built-in functions to perform type casting explicitly, which is useful when you want to ensure that a variable has a specific data type.
Why Casting is Needed?
Python is dynamically typed, meaning variables are assigned data types automatically based on the value. However, sometimes you may need to convert a value to a specific type explicitly. For example:
- Converting a string input to an integer for arithmetic operations.
- Converting a float to an integer for rounding purposes.
Types of Casting in Python
Python supports two types of casting:
- Implicit Casting
Python automatically converts one data type to another when no data loss occurs. - Explicit Casting
You use built-in functions to convert a value from one type to another.
1. Implicit Casting (Automatic Conversion)
Implicit casting is performed automatically by Python. For example, when a smaller data type (e.g., int
) is added to a larger data type (e.g., float
), Python promotes the smaller data type.
Example:
# Implicit type conversion
x = 5 # int
y = 2.5 # float
result = x + y # Python automatically converts 'x' to float
print(result) # Output: 7.5
print(type(result)) # Output: <class 'float'>
Key Point: Python avoids implicit conversion when it leads to data loss, like converting a float
to an int
.
2. Explicit Casting (Manual Conversion)
In explicit casting, you explicitly use Python’s built-in functions to convert data types.
Function | Description |
---|---|
int(x) | Converts x to an integer. |
float(x) | Converts x to a floating-point number. |
str(x) | Converts x to a string. |
bool(x) | Converts x to a boolean value. |
complex(x) | Converts x to a complex number. |
Examples of Explicit Casting
1. Casting to Integer (int
)
- Converts floats, strings, or booleans to integers.
- Note: Decimal values are truncated (not rounded).
Example:
# Float to Integer
x = 5.9
y = int(x)
print(y) # Output: 5
# String to Integer
num_str = "10"
num = int(num_str)
print(num) # Output: 10
# Boolean to Integer
print(int(True)) # Output: 1
print(int(False)) # Output: 0
2. Casting to Float (float
)
- Converts integers, strings, or booleans to floats.
Example:
# Integer to Float
x = 5
y = float(x)
print(y) # Output: 5.0
# String to Float
num_str = "7.5"
num = float(num_str)
print(num) # Output: 7.5
# Boolean to Float
print(float(True)) # Output: 1.0
print(float(False)) # Output: 0.0
3. Casting to String (str
)
- Converts any data type to a string.
Example:
# Integer to String
x = 123
y = str(x)
print(y) # Output: "123"
print(type(y)) # Output: <class 'str'>
# Float to String
pi = 3.14
pi_str = str(pi)
print(pi_str) # Output: "3.14"
# Boolean to String
print(str(True)) # Output: "True"
print(str(False)) # Output: "False"
4. Casting to Boolean (bool
)
- Converts values to boolean:
0
,0.0
,None
, and""
(empty string) →False
- Non-zero numbers and non-empty strings →
True
Example:
# Integers to Boolean
print(bool(0)) # Output: False
print(bool(10)) # Output: True
# Strings to Boolean
print(bool("")) # Output: False (empty string)
print(bool("Hello")) # Output: True (non-empty string)
# Floats to Boolean
print(bool(0.0)) # Output: False
print(bool(3.14)) # Output: True
5. Casting to Complex (complex
)
- Converts numbers or strings to complex numbers (
a + bj
).
Example:
# Integer to Complex
x = 5
y = complex(x)
print(y) # Output: (5+0j)
# Float to Complex
z = complex(3.14)
print(z) # Output: (3.14+0j)
# Real and Imaginary parts
num = complex(3, 4) # 3 is real, 4 is imaginary
print(num) # Output: (3+4j)
print(num.real) # Output: 3.0
print(num.imag) # Output: 4.0
Practical Example
Here’s an example to demonstrate different conversions:
# User Input as String
age_str = input("Enter your age: ") # Input is always a string
age = int(age_str) # Explicitly convert to integer
# Arithmetic Operation
new_age = age + 1
print("Next year, you will be:", new_age)
# Float Conversion
salary_str = "55000.75"
salary = float(salary_str)
print("Your salary is:", salary)
# Boolean Conversion
print(bool(0)) # Output: False
print(bool(10)) # Output: True
print(bool("")) # Output: False
print(bool("Hi")) # Output: True
Key Notes
- String Casting: The string must represent a valid number for conversion to
int
orfloat
. Otherwise, it will raise aValueError
.x = "abc" print(int(x)) # ValueError: invalid literal for int()
- Data Loss: When casting from
float
toint
, the decimal part is truncated (not rounded). - Boolean Rules:
0
,0.0
,None
, or empty values →False
- Everything else →
True
Summary Table
Function | Converts To | Example | Result |
---|---|---|---|
int() | Integer | int(5.9) | 5 |
float() | Floating-point | float("3.14") | 3.14 |
str() | String | str(100) | "100" |
bool() | Boolean | bool(0) | False |
complex() | Complex Number | complex(3, 4) | (3+4j) |
This explanation provides a clear understanding of Python Casting, with detailed examples and notes.