Type casting means converting a value from one data type to another, such as from a string to an integer. It is essential when working with user input, files, APIs, and mathematical operations.
Example problem without casting:
age = input("Enter your age: ")
print(age + 5) # ❌ Error: can't add string and integer
Correct version with casting:
age = int(input("Enter your age: "))
print(age + 5) # ✅ Works
You often need type casting when:
input(), which returns strings)Python sometimes converts types automatically (implicit casting), mainly in numeric expressions.
Python converted int to float automatically.
Explicit casting means you manually convert a value to a specific type using built-in functions.
| Function | Converts To |
|---|---|
int() | Integer |
float() | Floating-point number |
str() | String (text) |
bool() | Boolean (True or False) |
list() | List |
tuple() | Tuple |
set() | Set |
int()Use int() to convert values to whole numbers.
print(int("100")) # 100
print(int(5.8)) # 5 (decimal part is removed)
print(int(True)) # 1
print(int(False)) # 0
int("hello") # ValueError
int("10.5") # ValueError
Only strings that represent whole numbers (like "100") can be cast directly to int.
float()
float() converts values to floating-point numbers (decimals).
str()Almost any value can be converted to a string.
This is especially important for concatenating numbers with text (e.g., for printing or logging).
bool()Python decides if a value is truthy or falsy when converting to bool.
These are considered False:
0, 0.0"" (empty string)[], (), {}, set() (empty containers)NoneFalseEverything else is True:
print(bool(0)) # False
print(bool("")) # False
print(bool(10)) # True
print(bool("Hello")) # True
The input() function always returns a string, so you must cast it when working with numbers. Add 2 numbers input by the user:
Or using float() for decimal values. Add 2 decimal numbers input by the user:
You can convert between different collection types using built-in functions.
Convert a string into a list of characters.
Convert a list into a tuple.
Convert a list into a set to remove duplicate values.
When you get numbers as strings, you must cast them before doing math.
type() and isinstance()You can check the current type before or after casting.
Using isinstance():
try / except
Sometimes a string might not contain a valid number. Use try / except to avoid crashes.
A simple program that takes two numbers as input, adds them, and handles invalid input gracefully.
| Mistake | Wrong | Correct |
|---|---|---|
| Adding string and integer | |
|
| Invalid numeric string | |
|
Misunderstanding bool() |
|
|
In this guide, you learned how to:
type(), isinstance(), and try/except for safe castingType casting is essential for writing clean, safe, and correct Python programs, especially when working with user input and external data.