Type casting in Python means converting a value from one data type to another, such as int to float, str to int, or numbers and collections to bool. Practicing these conversions helps you avoid type errors and write more flexible, reusable code.
Python mainly uses explicit casting via built-in functions like int(), float(), str(), bool(), list(), tuple(), and set().
int and float."20" to numbers.bool() to check truthiness of values.list, tuple, and set.Common casting functions in Python:
int(x) – converts x to an integer (truncates decimals).float(x) – converts x to a floating-point number.str(x) – converts x to a string.bool(x) – converts x to a Boolean (True or False).list(x), tuple(x), set(x) – convert between collection types.This example shows how to convert between int, float, and str.
x = 10 # int
y = 3.5 # float
z = "20" # string
# int to float
print(float(x)) # 10.0
# float to int
print(int(y)) # 3
# string to int
print(int(z)) # 20
# int to string
print(str(x)) # "10"
Use bool() to check whether values are considered “truthy” or “falsy”.
print(bool(0)) # False
print(bool(10)) # True
print(bool("")) # False
print(bool("Hello")) # True
In general, zero, empty strings, and empty collections are False. Most other values are True.
Python allows you to freely convert between lists, tuples, and sets using their constructors.
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
my_set = set(my_list)
print(my_tuple) # (1, 2, 3)
print(my_set) # {1, 2, 3}
tuple() creates an immutable ordered sequence, while set() creates an unordered collection of unique elements.
float(10) becomes 10.0, and int(3.5) becomes 3 (decimal part discarded).int("20") works because "20" is a valid numeric string.bool(0) is False, but bool(10) is True. Similarly, bool("") is False and bool("Hello") is True.tuple([1, 2, 3]) prints (1, 2, 3), and set([1, 2, 3]) prints something like {1, 2, 3} (order may vary).Use these small snippets as starting points for your own practice.
# Convert a string input to integer and add 10
user_input = input("Enter a number: ")
num = int(user_input)
print(num + 10)
# Convert a float to integer and print
value = 7.9
print(int(value))
# Convert a list to tuple and set
items = [1, 2, 2, 3]
print(tuple(items))
print(set(items))
# Check truthiness of various values using bool()
print(bool([])) # False
print(bool([1, 2])) # True
print(bool(0.0)) # False
print(bool("Python")) # True
int(), float(), str(), and bool() for basic conversions.list, tuple, and set can be converted using their respective constructors.int() or float().int() on a float truncates the decimal part (it does not round).bool() to quickly check whether inputs or collections are empty or non-empty.int, add 10, and print the result.int, and observe how the value changes.tuple, convert it to a list, append a new item, and print both versions.[], [0], (), (1,), {}, and {"key": "value"}.