SwadhyAI Notes

All Python notes

Python Casting 🔄

What is Casting?

Casting is the process of converting a variable from one data type to another. This is useful when you need to treat a number as a string (for concatenation) or a string as a number (for math).

✨ Explicit Casting

You can force a type conversion using constructor functions:

To Integer

python
int(1)      # 1
int(2.8)    # 2
int("3")    # 3

To Float

python
float(1)    # 1.0
float(2.8)  # 2.8
float("3")  # 3.0

To String

python
str("s1")   # 's1'
str(2)      # '2'
str(3.0)    # '3.0'

🔄 Implicit Casting

Python automatically converts one data type to another when it makes sense. For example, adding an integer to a float results in a float.

python
x = 1    # int
y = 2.5  # float

z = x + y
print(z)        # 3.5
print(type(z))  # <class 'float'>

🔡 ASCII and Unicode

You can convert characters to their ASCII/Unicode integer value and vice versa.

python
print(ord('A'))  # 65 (Character to Integer)
print(chr(65))   # 'A' (Integer to Character)

⚠️ Watch Out: Data Loss

When converting a float to an integer, Python truncates the decimal part (rounds down towards zero). It does not round to the nearest number.

python
print(int(9.99))  # Output: 9 (Not 10!)

🎯 Real-World Application: User Input

The input() function always returns a string. If you ask a user for their age, you MUST cast it to an integer before doing math.

python
age = input("Enter your age: ")  # age is "25" (str)
# next_year = age + 1        # ❌ Error!
next_year = int(age) + 1     # ✅ Correct