Python Type Conversion

What is Type Conversion?

Type conversion means converting a value from one data type to another. In Python, this is often called typecasting.

Types of Type Conversion

Implicit Conversion Examples

# Python automatically converts int to float in expressions
a = 5     # int
b = 2.5   # float
c = a + b # a converted to float automatically
print(c)  # Output: 7.5 (float)
print(type(c))  # <class 'float'>

Explicit Conversion Examples

# Convert float to int (note: decimal part is truncated)
f = 9.8
i = int(f)
print(i)  # Output: 9

# Convert int to float
i = 5
f = float(i)
print(f)  # Output: 5.0

# Convert int to string
i = 100
s = str(i)
print(s)  # Output: "100"

# Convert string to int (string must represent a valid integer)
s = "42"
i = int(s)
print(i)  # Output: 42

# Convert string to float
s = "3.14"
f = float(s)
print(f)  # Output: 3.14

# Convert other types to boolean
print(bool(0))      # False
print(bool(10))     # True
print(bool(""))     # False
print(bool("False")) # True (non-empty string)

Common Type Conversion Functions

Important Notes

Example: User Input Conversion

# Get two numbers as input and add them

num1 = input("Enter first number: ")  # input returns string
num2 = input("Enter second number: ")

# Convert strings to int before adding
sum_ = int(num1) + int(num2)

print("Sum is:", sum_)

Best Practices