Python · Type Casting

Complete Guide to Python Type Casting

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.

1. Why Type Casting Is Important

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:

2. Implicit Type Casting

Python sometimes converts types automatically (implicit casting), mainly in numeric expressions.

Python converted int to float automatically.

3. Explicit Type Casting

Explicit casting means you manually convert a value to a specific type using built-in functions.

FunctionConverts To
int()Integer
float()Floating-point number
str()String (text)
bool()Boolean (True or False)
list()List
tuple()Tuple
set()Set

4. Casting to Integer: 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

❌ Invalid conversions

int("hello")   # ValueError
int("10.5")    # ValueError

Only strings that represent whole numbers (like "100") can be cast directly to int.

5. Casting to Float: float()

float() converts values to floating-point numbers (decimals).

6. Casting to String: 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).

7. Casting to Boolean: bool()

Python decides if a value is truthy or falsy when converting to bool.

These are considered False:

Everything else is True:

print(bool(0))        # False
print(bool(""))       # False
print(bool(10))       # True
print(bool("Hello"))  # True

8. Casting User Input

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:

9. Converting Between Data Structures

You can convert between different collection types using built-in functions.

9.1 String → List

Convert a string into a list of characters.

9.2 List → Tuple

Convert a list into a tuple.

9.3 List → Set (remove duplicates)

Convert a list into a set to remove duplicate values.

10. Casting in Arithmetic Operations

When you get numbers as strings, you must cast them before doing math.

11. Checking Types with type() and isinstance()

You can check the current type before or after casting.

Using isinstance():

12. Safe Casting with try / except

Sometimes a string might not contain a valid number. Use try / except to avoid crashes.

13. Real-World Example: Number Sum Calculator

A simple program that takes two numbers as input, adds them, and handles invalid input gracefully.

14. Common Type Casting Mistakes

MistakeWrongCorrect
Adding string and integer
"5" + 3
int("5") + 3
Invalid numeric string
int("abc")
try:\n    int("abc")\nexcept ValueError:\n    print("Invalid")
Misunderstanding bool()
bool("False")  # True, not False
# Use your own logic instead\nvalue = "False"\nif value == "False":\n    flag = False

15. Summary

In this guide, you learned how to:

Type casting is essential for writing clean, safe, and correct Python programs, especially when working with user input and external data.