Python

In Python, Type Casting (also known as Type Conversion) is the process of converting a variable from one data type to another. This is essential because Python is dynamically typed, and you often need to reconcile different types to perform operations (like adding a string number to an integer).

There are two primary types of conversion in Python:

1. Implicit Type Conversion

This is performed automatically by the Python interpreter without any user intervention. Python converts a "smaller" data type to a "larger" data type to prevent data loss.

  • Example: Adding an int and a float results in a float.

Python
num_int = 10
num_float = 1.5

# Python automatically converts num_int to float
result = num_int + num_float

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

2. Explicit Type Conversion

Also known as Type Casting, this is where the user manually converts the data type using built-in functions. This is necessary when Python cannot automatically handle the conversion (e.g., converting a string "5" to an integer 5).

Common Casting Functions

FunctionDescriptionExample
int()Converts to an integerint("10") → 10
float()Converts to a floating-point numberfloat(5) → 5.0
str()Converts to a stringstr(100) → "100"
list()Converts a sequence to a listlist("abc") → ['a', 'b', 'c']
tuple()Converts a sequence to a tupletuple([1, 2]) → (1, 2)
bool()Converts to a booleanbool(1) → True

Code Implementation

Python
# String to Integer
age_str = "25"
age_int = int(age_str)
print(age_int + 5) # Output: 30

# Integer to Float
price = 100
price_float = float(price)
print(price_float) # Output: 100.0

# Float to Integer (Note: This truncates/drops the decimal)
pi = 3.99
pi_int = int(pi)
print(pi_int)      # Output: 3 (not 4)

# Data to String
score = 95
message = "Your score is " + str(score)
print(message)     # Output: Your score is 95

Important Considerations

  • Loss of Data: Converting a float to an int removes the decimal part (it does not round).

  • ValueErrors: You cannot cast a string that doesn't "look" like a number into an integer.

    • int("10") works.

    • int("Apple") will raise a ValueError.

  • Boolean Logic: In Python, bool(0), bool(None), and bool("") (empty string) are False. Almost everything else is True.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now