What is Type Casting?
Imagine you have a magical potion that can transform objects into different forms. In Python, type casting (or type conversion) allows you to change a value’s data type, like turning a pumpkin into a carriage (or an integer into a float).
Python provides built-in functions to convert one data type to another:
int()
→ Converts to an integer (whole number)float()
→ Converts to a floating-point (decimal number)str()
→ Converts to a string (text)bool()
→ Converts to a boolean (True
orFalse
)
Converting to an Integer (int
)
If you have a string or a float and need an integer, you can use int()
.
Example:
num_str = "42"
num_int = int(num_str) # Converts string "42" to integer 42
print(num_int) # Output: 42
Be careful when converting from float to int:
num_float = 3.99
num_int = int(num_float)
print(num_int) # Output: 3 (Python TRUNCATES, no rounding!)
Important: If you try to convert a non-numeric string, Python will complain:
num = int("Hello") # ERROR: ValueError
Converting to a Float (float
)
Need decimals? Use float()
to convert an integer or a string.
Example:
num_int = 10
num_float = float(num_int) # Converts 10 to 10.0
print(num_float) # Output: 10.0
Works with strings too:
num_str = "3.14"
num_float = float(num_str)
print(num_float) # Output: 3.14
Trying to convert a string that isn’t a number?
num = float("Hello") # ERROR: ValueError
Converting to a String (str
)
Need to turn numbers into text? str()
is your friend.
Example:
age = 25
age_str = str(age)
print("I am " + age_str + " years old.") # Output: I am 25 years old.
This is useful when printing or combining text with numbers.
price = 9.99
print("The price is $" + str(price)) # Output: The price is $9.99
Converting to a Boolean (bool
)
Python considers some values as False
and others as True
:
False values:
0
""
(empty string)None
False
Everything else is True
:
print(bool(0)) # Output: False
print(bool(1)) # Output: True
print(bool("")) # Output: False
print(bool("Hello")) # Output: True
Even non-empty lists and dictionaries are True
:
print(bool([])) # Output: False (empty list)
print(bool([1, 2])) # Output: True (non-empty list)
Summary
Function | Converts To |
---|---|
int(x) |
Integer (removes decimals if float) |
float(x) |
Float (adds .0 if integer) |
str(x) |
String |
bool(x) |
Boolean (False for 0 , "" , None ; True otherwise) |
Now you know how to cast and convert data types in Python like a pro!
0 Comments