Python Mastery – From Basics to Brilliance / Python Fundamentals

Type Casting

What is Type Casting?

Type Casting is the process of converting a variable from one data type to another (for example, turning a string "10" into an integer 10).

In Python, there are two types of type casting:

  1. Implicit Type Conversion (Done automatically by Python)

  2. Explicit Type Conversion (Done manually by you)

1. Implicit Type Conversion (Automatic)

Python automatically converts one data type to another to prevent data loss.

  • How it works: If you add an integer and a float, Python automatically converts the integer to a float.

num_int = 5        # Integer
num_flo = 2.5      # Float

# Python automatically converts num_int to float before adding
result = num_int + num_flo  

print(result)      # Output: 7.5
print(type(result)) # Output: <class 'float'>

2. Explicit Type Conversion (Manual)

This is what we usually mean by "Type Casting." You use built-in Python functions to force a data type change.

Common Type Casting Functions

Function

What it does

Example

Output

int()

Converts to an Integer

int("15")

int(3.9)

15

3 (floats are truncated, not rounded)

float()

Converts to a Float

float(7)

float("4.2")

7.0

4.2

str()

Converts to a String

str(100)

str(5.5)

"100"

"5.5"

bool()

Converts to a Boolean

bool(1)

bool(0)

bool("")

True

False

False (empty values are False)

Key Rules & Gotchas

⚠️ The Value Must Make Sense: You can only convert a string to an integer if the string looks like a number.

  • int("123") works perfectly.

  • int("apple") will crash your code with a ValueError.

  • Boolean Truths: When casting to bool(), numbers equal to 0 and empty items (like "", [], {}) become False. Almost everything else becomes True.


Why do we need it? (A Practical Example)

By default, user input in Python always comes in as a string. If you want to do math with it, you must type cast it.

# Without Type Casting (This will cause an error or weird behavior)
age = input("Enter your age: ") # User enters 20 -> age is "20" (string)
# next_year = age + 1          # ERROR: Cannot add string and integer

# With Type Casting
age = int(input("Enter your age: ")) # Converts the string "20" to integer 20
next_year = age + 1                  # Works perfectly! (21)