Python Casting
3 min read ·
Python casting means converting a value from one data type to another.
It is mainly used when you want to specify a variable type explicitly instead of relying on automatic type detection.
Casting is extremely important while:
- Taking user input
- Performing calculations
- Cleaning and validating data
Specify a Variable Type
Python allows you to specify a variable’s data type by using built-in casting functions.
Common casting functions:
int()float()str()bool()
Casting Integer (int)
Converts a value into an integer.
Hidden Fact
True becomes 1 and False becomes 0 when cast to int.
Casting Float (float)
Converts a value into a floating-point number.
Casting String (str)
Converts a value into a string.
Casting Boolean (bool)
Converts a value into
True or False.Important Rule
0,None,"",[],{}→False- Everything else →
True
Casting Collections (Less Known but Powerful)
Many students don’t know you can cast between collection types.
List Casting
Tuple Casting
Set Casting (Unique Values Only)
Casting with type() (Advanced Insight)
Many students don’t know you can check casting results dynamically.
User Input Casting (Very Important)
User input is always a string, even if you enter a number.
Common Casting Errors (Hidden Traps)
Correct way:
New Concept Many Students Don’t Know
eval() for Dynamic Casting (Use Carefully)
eval() converts a string into a Python expression.Security Warning
Never use eval() on user input. It can execute harmful code.
Exercise
- Convert a string number to integer
- Convert a word into a list
- Convert
Trueto integer and float - Use
eval()safely with a numeric expression