Day-2 - Type Casting in Python


In Python, type casting (also known as type conversion) is the process of converting a value from one data type to another.
This is especially useful when working with user input, mathematical operations, or when you need to ensure data is in the right format.
Why Do We Need Type Casting? ๐ค
Consider this example:
age = input("Enter your age: ")
print(age + 5) # โ Error
Here, input()
always returns a string, even if you enter a number. Trying to add a string and an integer will throw an error.
โ Solution: Convert the string into an integer using type casting:
age = int(input("Enter your age: "))
print(age + 5) # Works fine
Types of Type Casting in Python
Python supports two types of conversions:
1. Explicit Type Casting (Manual Conversion)
You manually convert values using built-in functions like int()
, float()
, str()
, bool()
.
๐ Example:
# String to Integer
print(int("100")) # 100
# Float to Integer (decimal part removed)
print(int(9.99)) # 9
# Integer to String
print(str(123)) # "123"
# Number to Boolean
print(bool(0)) # False
print(bool(5)) # True
2. Implicit Type Casting (Automatic Conversion)
Sometimes, Python automatically converts data types during operations.
๐ Example:
x = 10 # Integer
y = 2.5 # Float
result = x + y
print(result) # 12.5
print(type(result)) # <class 'float'>
Here, Python automatically promotes the integer (10
) into a float so that both operands are of the same type.
Common Conversion Functions
int()
โ Converts values into integers (removes decimals, errors on invalid strings).float()
โ Converts values into floating-point numbers.str()
โ Converts numbers, booleans, or other objects into strings.bool()
โ Converts values intoTrue
orFalse
.
Edge Cases โก
Converting an invalid string to a number โ โ Error
print(int("abc")) # ValueError
Boolean conversion rules:
print(bool("")) # False (empty string) print(bool("Hi")) # True (non-empty string) print(bool(0)) # False print(bool(42)) # True
Float to int always truncates, not rounds:
print(int(9.99)) # 9 print(int(-3.9)) # -3
Quick Recap ๐
Type Casting = Converting one data type into another.
Explicit Casting โ Done using functions (
int()
,float()
,str()
,bool()
).Implicit Casting โ Done automatically by Python during operations.
Be mindful of edge cases (invalid strings, float truncation, boolean rules).
โจ With type casting, Python gives you complete control over how data behaves in your program โ making it flexible, safe, and beginner-friendly!
Subscribe to my newsletter
Read articles from Raviteja Vaddamani directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
