Python Casting

1. What is Casting in Python?

Casting means changing one data type into another.

Example:

  • Text → Number

  • Number → Text

Python uses casting when we need to do calculations or print values correctly.

2. Why Do We Need Casting?

User input is always text (string).

Example:

age = input("Enter age: ")
print(age + 1)

❌ This gives an error because Python cannot add text + number.

So we use casting.

3. String to Integer (int())

Convert text to whole number.

Example

x = "10"
y = int(x)
print(y + 5)

Output:

15

User Input Example

age = int(input("Enter your age: "))
print("Next year:", age + 1)

4. String to Float (float())

Convert text to decimal number.

Example

price = "19.99"
new_price = float(price)
print(new_price + 10)

User Input Example

radius = float(input("Enter radius: "))
print("Area:", 3.14 * radius * radius)

5. Integer to Float

Example

a = 5
b = float(a)
print(b)

Output:

5.0

6. Float to Integer

Decimal part is removed (not rounded).

Example

x = 12.7
y = int(x)
print(y)

Output:

12

7. Number to String (str())

Convert number to text.

Example

age = 25
print("Age is " + str(age))

8. Checking Type After Casting

Use type() to check data type.

Example

x = 10
print(type(x))
x = str(x)
print(type(x))

9. Common Casting Errors (Beginners)

❌ Invalid Conversion

x = "hello"
y = int(x)

❌ Error because “hello” is not a number.

✔ Correct Way

x = "123"
y = int(x)

10. Simple Practice Examples

Example 1: Add Two Numbers from Input

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(“Sum:”, a + b)

Example 2: Convert Float to Int

price = 99.9
price = int(price)
print(price)

Example 3: Print with String Conversion

marks = 85
print("Marks:", str(marks))

11. Summary (Python Casting)

✔ Casting means changing data type
✔ Input is string by default
int() converts to number
float() converts to decimal
str() converts to text

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Python Strings (easy)

  • Python Booleans

  • Operators

  • Casting Exercises

  • MCQs with answers

Just tell me 😊

You may also like...