🐍 Lesson 8: Python Casting
1. What is casting?
Short answer → Casting means converting the value in a variable into a different data type.
In other words → Casting means converting a variable from one data type to another.
2. Python's Built-in Casting Functions
int()→ converts a value to an integerfloat()→ converts a value to a floatstr()→ converts a value to a string
3. Converting a String to a Number
You can convert a string as long as it only contains digits.
Trying to convert non-numeric text with int/float will raise an Error.
4. Summary
✅ Casting = converting a data type
✅ int(), float(), str() are the ones to use
✅ To convert a string to a number, it must contain only digits
✅ You should cast user input before using it
python
# ===== 1. Basic Casting Examples =====
# int() → ဒဿမကို ကိန်းပြည့် ပြောင်း
x = int(3.9)
print(f"int(3.9) = {x}") # 3
# float() → ကိန်းပြည့်ကို ဒဿမ ပြောင်း
y = float(5)
print(f"float(5) = {y}") # 5.0
# str() → ကိန်းကို စာသား ပြောင်း
z = str(10)
print(f"str(10) = '{z}', Type: {type(z)}") # "10"
# ===== 2. String to Number =====
print(f"\n===== String to Number =====")
a = int("100")
print(f"int('100') = {a}") # 100
b = float("3.14")
print(f"float('3.14') = {b}") # 3.14
# ===== 3. Practical Use Case =====
print(f"\n===== User Input Example =====")
# Simulating user input
user_age = "25" # input() returns string
age = int(user_age) # Convert to int
next_year = age + 1
print(f"Current age: {age}")
print(f"Next year: {next_year}")You should see
int(3.9) = 3 float(5) = 5.0 str(10) = '10', Type: ===== String to Number ===== int('100') = 100 float('3.14') = 3.14 ===== User Input Example ===== Current age: 25 Next year: 26