Python Casting
Casting in Python refers to converting a variable from one data type to another. Unlike some languages, Python does this using built-in functions. This is useful when you need to convert data for calculations, comparisons, or formatting.
Why Casting is Important
When working with different data types, you may need to:
- Convert strings to numbers for calculations
- Format floats as strings for output
- Change integers to floats for division
Basic Casting Functions
Python provides several built-in functions for type conversion:
Function | Converts To |
---|---|
int() | Integer |
float() | Floating point number |
str() | String |
bool() | Boolean |
1. Converting to Integer: int()
x = int(3.7) # x = 3
y = int("10") # y = 10
❗
int("abc")
will raise aValueError
because "abc" cannot be converted to a number.
2. Converting to Float: float()
x = float(5) # x = 5.0
y = float("3.14") # y = 3.14
3. Converting to String: str()
x = str(100) # x = "100"
y = str(3.14) # y = "3.14"
4. Converting to Boolean: bool()
bool(0) # False
bool(1) # True
bool("") # False
bool("Hello") # True
Rule of Thumb: 0
, None
, ""
, []
, {}
, and ()
are considered False
; everything else is True
.
Example in Action
a = "10"
b = "5.5"
# Convert to proper types
a = int(a)
b = float(b)
# Perform operation
result = a + b
print(result) # 15.5
Things to Watch Out For
1. Not all strings can be converted to numbers:
int("abc") # ValueError
2. Casting a float to int truncates (doesn't round):
int(3.99) # 3
Test Yourself
Try to guess the output before running:
print(int("5") + float("2.3"))
print(str(10) + str(20))
print(bool("False"))
Summary
- Use
int()
,float()
,str()
, andbool()
for conversions. - Always validate input if it's coming from a user or external source.
- Remember type conversion can cause data loss (like float to int).