Python Casting

🐍 Python Casting (Type Conversion)

In Python, casting means converting a value from one data type to another.
For example, converting a string "10" to an integer 10.

Python has built-in functions to cast data types:

Function Converts to
int() Integer (whole number)
float() Decimal number
str() String

✅ 1. Casting to Integer — int()

Use int() when you want to convert values into whole numbers.

x = int(3.5) # Converts float to int → 3
y = int("10") # Converts string to int → 10
print(x, type(x))
print(y, type(y))

⚠️ Note: You cannot convert strings containing letters:

int("10a") # ❌ ERROR

✅ 2. Casting to Float — float()

Use float() to convert values into decimal numbers.

a = float(5) # Converts int to float → 5.0
b = float("12.75") # Converts string to float → 12.75
print(a, type(a))
print(b, type(b))

✅ 3. Casting to String — str()

Use str() to convert values into text format.

p = str(10)
q = str(55.50)
print(p, type(p))
print(q, type(q))

📌 Examples of Casting in Real Life Programs

Example 1: Input Conversion

age = input("Enter your age: ") # Input always gives string
age = int(age) # Convert to number
print(“Next year your age will be:”, age + 1)

Example 2: Mathematical Calculation with Casting

num1 = "100"
num2 = "50"
result = int(num1) + int(num2)print(result) # Output: 150


🔁 Mixed Conversion Example

x = 10
y = 3.5
print(str(x) + ” and “ + str(y)) # Converts both to string for printing

🧠 Summary Table

Data int() float() str()
"10"
"10.5"
10
10.5 ✔ (→10)
"abc"

🎉 Final Example

a = "20"
b = 15
result = int(a) + b
print(result) # Output: 35

You may also like...