Loading lesson…
ការបំប្លែងប្រភេទ
Python variables have types, but you can convert between them using built-in functions. This is called type casting.
age_str = "22" # str age_int = int(age_str) # → 22 (int) price = 9.99 price_int = int(price) # → 9 (truncates decimal!) num = 42 num_str = str(num) # → "42" (str) is_valid = bool(1) # → True is_empty = bool(0) # → False
When you use input(), Python gives you a str even if the user types a number. Always convert: age = int(input("Enter age: "))
❌ Bug — comparing str to int
age = input("Age: ")
if age > 18: # TypeError!
print("Adult")✅ Fix — convert first
age = int(input("Age: "))
if age > 18: # works!
print("Adult")