Type Casting
3 min read ·
In Python, you can explicitly set (force) a specific data type for a variable using type casting.
This is useful when working with user input, data conversion, calculations, or formatting output.
Python provides built-in functions to convert one data type into another.
What Is Type Casting?
Type casting means converting one data type into another using built-in functions.
Common casting functions:
int()float()str()bool()list()tuple()set()dict()
Definition
Type casting allows you to control the data type of a variable explicitly.
Setting Integer Type (int)
Used to convert values into integers.
Note
Strings must contain only numbers to convert to int.
Setting Float Type (float)
Used to convert values into floating-point numbers.
Setting String Type (str)
Used to convert values into strings.
Setting Boolean Type (bool)
The
bool() function converts values to True or False.Rule
0,None, empty string →False- Everything else →
True
Setting List Type (list)
Used to convert iterable objects into a list.
Setting Tuple Type (tuple)
Used to convert iterable objects into a tuple.
Setting Set Type (set)
Used to convert iterable objects into a set (unique values only).
Setting Dictionary Type (dict)
Used to create dictionaries from key-value pairs.
Setting Complex Type (complex)
Used to create complex numbers.
Casting User Input (Very Important)
User input is always treated as a string.
Common Casting Errors
Invalid Conversion
Safe Conversion Example
Caution
Always validate input before casting to avoid runtime errors.
Why Setting Data Types Is Important
Setting specific data types helps to:
- Avoid runtime errors
- Perform correct calculations
- Handle user input properly
- Write predictable and clean code
Key Takeaway
Type casting gives you full control over how data is stored and processed.
Exercise
- Convert a string number into integer
- Convert an integer into float
- Convert a word into a list
- Check boolean value of empty and non-empty strings