ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Casting ဆိုတာ value တစ်ခုကို type တစ်မျိုးကနေ နောက်တစ်မျိုး ပြောင်းတာပါ။ ဥပမာ "25" ဆိုတဲ့ စာသားက လူအတွက် ကိန်းနဲ့ တူပေမယ့် Python အတွက်တော့ စာလုံးနှစ်လုံး ပါတဲ့ string ပဲ ဖြစ်ပါတယ်။ int("25") လို့ ခေါ်လိုက်မှ ပေါင်းလို့ နုတ်လို့ရတဲ့ ကိန်း 25 ဖြစ်လာပါတယ်။
Python မှာ ပြောင်းချင်တဲ့ type ရဲ့ နာမည်ကို function လို ခေါ်ရုံပါပဲ — int()၊ float()၊ str()၊ bool()။ ဒီ function တွေက မူရင်း value ကို မပြောင်းဘဲ type အသစ်နဲ့ value အသစ်တစ်ခုကို ပြန်ပေးပါတယ်၊ ဒါကြောင့် ရလဒ်ကို variable တစ်ခုထဲ သိမ်းဖို့ မမေ့ပါနဲ့။
Problem → Why → Solution
ပြဿနာ: input() က ကိန်းမဟုတ်ဘဲ string ပြန်ပေးတယ်
User ရဲ့ အသက်ကို မေးပြီး နောက်နှစ်ဆို ဘယ်လောက် ဖြစ်မလဲ တွက်တဲ့ program လေး ရေးလိုက်ပါတယ်။ User က 25 လို့ ရိုက်ထည့်ပေမယ့် program က 26 ကို မပြဘဲ TypeError နဲ့ ရပ်သွားပါတယ်။ အခြား နည်းနဲ့ စမ်းကြည့်တော့ age * 2 က 50 မဟုတ်ဘဲ "2525" ထွက်လာပါတယ်။ ပြဿနာက input() ဟာ user ဘာရိုက်ရိုက် string ကိုပဲ အမြဲ ပြန်ပေးလို့ပါ။
age = input("How old are you? ") # user types 25 -> age is "25"
print(age * 2) # 2525 (string repetition, not maths)
print(age + 1) # TypeError: can only concatenate str (not "int") to strဘာကြောင့် ဒီလို ဖြစ်တာလဲ
Python က type တစ်ခုကို နောက်တစ်ခု အလိုအလျောက် မပြောင်းပါဘူး။ string နဲ့ int ကို + နဲ့ ပေါင်းရင် စာဆက်ချင်တာလား၊ ကိန်းပေါင်းချင်တာလား မသိလို့ error ပေးပါတယ်။ string * int ကတော့ string ကို အကြိမ်ရေအတိုင်း ထပ်ပေးတာမို့ error မတက်ဘဲ မှားတဲ့ ရလဒ် ထွက်လာပါတယ်။ ဖြေရှင်းနည်းက user ပေးတဲ့ data ကို ရရချင်း int() ဒါမှမဟုတ် float() နဲ့ ပြောင်းလိုက်တာပါ။
Core concept: type နာမည်က converter function ပါ
int()၊ float()၊ str() နဲ့ bool() ဟာ class တွေဖြစ်ပြီး ခေါ်လိုက်တဲ့အခါ ထည့်ပေးတဲ့ value ကနေ type အသစ် object တစ်ခု တည်ဆောက်ပေးပါတယ်။ ပြောင်းလို့ ရမရ ဆိုတာ input ပေါ်မူတည်ပါတယ် — စည်းမျဉ်းတွေကို အောက်က table မှာ စုထားပါတယ်။
Python မှာ conversion နှစ်မျိုး ရှိပါတယ်။ Implicit conversion က number type တွေကြားမှာပဲ အလိုအလျောက် ဖြစ်ပါတယ် — 2 + 0.5 က တိတ်တိတ်လေး float 2.5 ဖြစ်သွားတာမျိုးပါ။ ကျန်တဲ့ နေရာတိုင်းမှာ၊ အထူးသဖြင့် text နဲ့ number ကြားမှာ explicit conversion ဖြစ်တဲ့ casting ကို ကိုယ်တိုင် လုပ်ရပါတယ်။
| ခေါ်ပုံ | ရလဒ် | မှတ်ချက် |
|---|---|---|
| int(3.9) | 3 | ဒသမကို ဖြတ်ချ၊ round မလုပ် |
| int(" 42 ") | 42 | ဘေးက space တွေကို လက်ခံ |
| int("3.5") | ValueError | ကိန်းပြည့် string ပဲ လက်ခံ |
| float("3.5") | 3.5 | "1e3" လို ပုံစံလည်း ရ |
| str(10) | "10" | ဘယ် value မဆို ရ |
| bool("False") | True | ဗလာမဟုတ်တဲ့ string အားလုံး True |
int() က string ကို ဖတ်တဲ့အခါ အရှေ့အနောက်က space၊ + ဒါမှမဟုတ် - sign နဲ့ 1_000 လို underscore တွေကို လက်ခံပါတယ်။ ဒါပေမယ့် ဒသမအမှတ် ပါနေတာ၊ စာလုံးတွေ ပါနေတာ ဆိုရင်တော့ ValueError: invalid literal for int() with base 10 ကို raise လုပ်ပါတယ်။ "3.7" ကို ကိန်းပြည့် လိုချင်ရင် int(float("3.7")) လို့ အဆင့်နှစ်ဆင့် ပြောင်းရပါတယ်။ int(None) လို type လုံးဝ မကိုက်တဲ့ value ကိုတော့ ValueError မဟုတ်ဘဲ TypeError ပေးပါတယ်။
Number → string ပြောင်းတာကတော့ ဘယ်တော့မှ မကျပါဘူး၊ str() က value တိုင်းကို စာသားအဖြစ် ပြပေးနိုင်ပါတယ်။ ဒါပေမယ့် text ထဲမှာ value တွေ ထည့်ချင်ရင် "Age: " + str(age) ထက် f"Age: {age}" က ပိုရှင်းပါတယ်၊ f-string က conversion ကို ကိုယ့်ဘာသာ လုပ်ပေးလို့ပါ။
bool() ကတော့ value ရဲ့ "ဗလာ ဖြစ်မဖြစ်" ကိုပဲ ကြည့်ပါတယ်၊ စာသားရဲ့ အဓိပ္ပာယ်ကို မဖတ်ပါဘူး။ "" တစ်ခုပဲ False ဖြစ်ပြီး "False"၊ "0"၊ "no" အားလုံး True ပါ။ Yes/No answer ကို boolean ပြောင်းချင်ရင် text.strip().lower() == "yes" လို နှိုင်းယှဉ်ချက်ကို ကိုယ်တိုင် ရေးရပါတယ်။
- အပြင်က data က string အဖြစ် ဝင်
- ဝင်ဝင်ချင်း int()/float() နဲ့ ပြောင်း
- မပြောင်းနိုင်ရင် ValueError ကို ဖမ်း
- အတွင်းမှာ number နဲ့ပဲ တွက်
Casting ကို program ရဲ့ အဝင်ပေါက်မှာ တစ်ကြိမ်တည်း လုပ်ရင် ကျန်တဲ့ code တစ်ခုလုံးက type မှန်တဲ့ data နဲ့ပဲ အလုပ်လုပ်ရပါတယ်။
အထွေထွေ ပုံစံ
number = int(text) # whole-number text -> int
real = float(text) # decimal text -> float
label = str(value) # anything -> str
flag = bool(value) # empty -> False, otherwise True
try:
number = int(raw_text)
except ValueError:
number = fallbackConversion function တိုင်းက value အသစ်ကို ပြန်ပေးလို့ variable ထဲ assign လုပ်ရပါတယ်။ အပြင်က ဝင်လာတဲ့ text ကို ပြောင်းတဲ့အခါ try/except ValueError နဲ့ ပတ်ထားရင် program crash မဖြစ်တော့ပါဘူး။
Example: number, string နဲ့ user input ပြောင်းခြင်း
ဒီ example မှာ int()၊ float()၊ str() ကို တစ်ခုချင်း စမ်းပြီး input() ကနေ ရလာသလို string "25" ကို ကိန်းပြောင်းကာ တွက်ပါတယ်။ နောက်ဆုံး အပိုင်းက int() လက်ခံတဲ့ text နဲ့ လက်မခံတဲ့ text တွေကို loop နဲ့ စမ်းပြပြီး try/except က error ကို ဘယ်လို ဖမ်းလဲ ပြပါတယ် — try/except ကို နောက် lesson တစ်ခုမှာ အသေးစိတ် လေ့လာပါမယ်။
# ===== 1. Basic Casting Examples =====
x = int(3.9) # float -> int (cuts off the decimals)
print(f"int(3.9) = {x}")
y = float(5) # int -> float
print(f"float(5) = {y}")
z = str(10) # int -> str
print(f"str(10) = '{z}', Type: {type(z)}")
# ===== 2. String to Number =====
print("\n===== String to Number =====")
a = int("100")
print(f"int('100') = {a}")
b = float("3.14")
print(f"float('3.14') = {b}")
# ===== 3. Practical Use Case =====
print("\n===== User Input Example =====")
user_age = "25" # input() always returns a str
age = int(user_age)
next_year = age + 1
print(f"Current age: {age}")
print(f"Next year: {next_year}")
# ===== 4. Text That Is Not a Whole Number =====
print("\n===== Invalid Text =====")
for text in [" 42 ", "3.5", "abc"]:
try:
print(f"int({text!r}) = {int(text)}")
except ValueError as err:
print(f"int({text!r}) failed: {err}")Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Line 2
x = int(3.9) # float -> int (cuts off the decimals)int() က float ရဲ့ ဒသမ အပိုင်းကို ဖြတ်ချလို့ 3.9 က 4 မဟုတ်ဘဲ 3 ဖြစ်ပါတယ်။
- Line 9
print(f"str(10) = '{z}', Type: {type(z)}")z က စာလုံး "1" နဲ့ "0" ပါတဲ့ string ပါ၊ type(z) က <class 'str'> ပြပါတယ်။ z + 5 လို့ ရေးရင် TypeError တက်ပါမယ်။
- Lines 21-22
age = int(user_age)user_age = "25" က input() ပြန်ပေးတဲ့ string ကို အတုလုပ်ထားတာပါ။ int() နဲ့ ပြောင်းပြီးမှ age + 1 က 26 ရပါတယ်။
- Line 29
for text in [" 42 ", "3.5", "abc"]:" 42 " က space ပါပေမယ့် int() က ဖယ်ပေးလို့ 42 ရပါတယ်။ "3.5" နဲ့ "abc" ကတော့ ကိန်းပြည့် text မဟုတ်လို့ ValueError ဖြစ်ပါတယ်။
- Lines 32-33
except ValueError as err:ValueError ကို ဖမ်းပြီး Python ရဲ့ error message ကို print ထုတ်တာမို့ program က ရပ်မသွားဘဲ နောက် text ကို ဆက်စမ်းပါတယ်။ {text!r} က quote ပါတဲ့ repr ပုံစံနဲ့ ပြလို့ space တွေကို မြင်ရပါတယ်။
int(3.9) = 3
float(5) = 5.0
str(10) = '10', Type: <class 'str'>
===== String to Number =====
int('100') = 100
float('3.14') = 3.14
===== User Input Example =====
Current age: 25
Next year: 26
===== Invalid Text =====
int(' 42 ') = 42
int('3.5') failed: invalid literal for int() with base 10: '3.5'
int('abc') failed: invalid literal for int() with base 10: 'abc'Base ပါတဲ့ int() နဲ့ collection conversion
int() ကို ဒုတိယ argument အဖြစ် base ပေးလို့ရပါတယ်။ int("ff", 16) က hexadecimal ကို 255 အဖြစ်၊ int("101", 2) က binary ကို 5 အဖြစ် ဖတ်ပါတယ်။ Base ကို 0 ပေးရင် "0x"၊ "0b" လို prefix ကနေ Python က ဆုံးဖြတ်ပေးပါတယ်။ Color code၊ permission bit တွေ ဖတ်တဲ့အခါ အသုံးဝင်ပါတယ်။
Type နာမည်ကို function လို ခေါ်တဲ့ နည်းက collection တွေမှာလည်း အလုပ်လုပ်ပါတယ်။ list("abc") က string ကို စာလုံးတစ်လုံးချင်း list ဖြစ်စေပြီး tuple([1, 2]) က list ကို tuple ပြောင်းပါတယ်။ ဒါတွေကို List နဲ့ Tuple lesson တွေမှာ ထပ်တွေ့ရပါမယ်။
print(int("ff", 16)) # 255
print(int("101", 2)) # 5
print(int("0x1F", 0)) # 31 (base read from the prefix)
print(list("abc")) # ['a', 'b', 'c']
print(tuple([1, 2])) # (1, 2)
print(int(float("3.7"))) # 3လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
Program အပြင်ကနေ ဝင်လာတဲ့ data အများစုက text ပါ — command-line argument (sys.argv)၊ environment variable (os.environ)၊ CSV file ရဲ့ column တွေ၊ web form field တွေ၊ URL query string တွေ အားလုံး string အဖြစ် ရောက်လာပါတယ်။ ဒါကြောင့် PORT = int(os.environ.get("PORT", "8000")) လို line တွေကို config file တိုင်းလိုလိုမှာ တွေ့ရပါတယ်။
Django၊ FastAPI လို framework တွေမှာ form နဲ့ request data ကို validate လုပ်တဲ့ layer က ဒီ casting ကို အလိုအလျောက် လုပ်ပေးပြီး မပြောင်းနိုင်ရင် user ကို error message ပြပါတယ်။ အတွင်းပိုင်းမှာတော့ int()/float() ကိုပဲ ခေါ်ပြီး ValueError ကို ဖမ်းတာပါပဲ။ Report ဒါမှမဟုတ် log ထုတ်တဲ့အခါမှာ ပြောင်းပြန် လုပ်ရပါတယ် — number တွေကို str() ဒါမှမဟုတ် f-string နဲ့ text ပြန်ပြောင်းပါတယ်။ Spreadsheet ကနေ data import လုပ်တာက ဒီနေရာမှာ bug အဖြစ်များတဲ့ နေရာပါ၊ 1,250 လို ပုံစံ cell ကို float() လက်ခံဖို့ comma ကို အရင် ဖယ်ရလို့ပါ။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. input() ရလဒ်ကို မပြောင်းဘဲ တွက်တာ
price = input("Price: ") ပြီးရင် price * 2 က "1010" လို string ထပ်ခြင်း ဖြစ်ပြီး price + 1 က TypeError ဖြစ်ပါတယ်။ price = float(input("Price: ")) လို့ တစ်ကြောင်းတည်းမှာ ပြောင်းလိုက်ပါ။
2. ဒသမ ပါတဲ့ text ကို int() နဲ့ ပြောင်းတာ
int("3.0") တောင် ValueError ပေးပါတယ်၊ int() က string ထဲမှာ ကိန်းပြည့်ပုံစံကိုပဲ လက်ခံလို့ပါ။ ဒသမ ပါနိုင်တဲ့ data ဆိုရင် float() နဲ့ ဖတ်ပြီး လိုအပ်မှ int() ဒါမှမဟုတ် round() ဆက်ခေါ်ပါ။
3. bool("False") က False ပြန်မယ်လို့ ထင်တာ
Config file ထဲက DEBUG=False ကို bool(os.environ["DEBUG"]) နဲ့ ဖတ်ရင် string က ဗလာမဟုတ်လို့ True ရပြီး debug mode က production မှာ ဖွင့်နေပါလိမ့်မယ်။ value.lower() in ("1", "true", "yes") လို နှိုင်းယှဉ်ချက်ကို သုံးပြီး ကျန်တာအားလုံးကို False အဖြစ် သတ်မှတ်ပါ။
Best Practices
အကောင်းဆုံး အလေ့အကျင့်များ
- အပြင်က data ကို program ထဲ ဝင်တဲ့ နေရာမှာ တစ်ကြိမ်တည်း ပြောင်းပါ၊ code အနှံ့ int() တွေ မဖြန့်ပါနဲ့။
- User ရိုက်ထည့်တဲ့ text ကို ပြောင်းရင် try/except ValueError နဲ့ ကာကွယ်ပြီး ရှင်းလင်းတဲ့ message ပြပါ။
- Text ထဲ number ထည့်ဖို့ str() နဲ့ + ထက် f-string ကို ပိုသုံးပါ။
Mini challenge
Mini challenge: form data ကို type မှန်အောင် ပြောင်းခြင်း
Web form ကနေ ရလာတဲ့ string dictionary တစ်ခုကို int, float, bool တွေအဖြစ် ဘေးကင်းကင်း ပြောင်းပေးတဲ့ helper function နှစ်ခု ရေးပါ။
- to_int(text, default=0) က ပြောင်းလို့ရရင် int ပြန်ပြီး ValueError ဖြစ်ရင် default ကို ပြန်ရမယ်
- to_bool(text) က "yes", "true", "1" (စာလုံးအကြီးအသေး၊ space မရွေး) ကိုပဲ True အဖြစ် လက်ခံရမယ်
- age, height_m, newsletter, pets လေးခုကို ပြောင်းပြီး value နဲ့ type နာမည်ကို print ထုတ်ရမယ်
- bool("No") ရဲ့ ရလဒ်ကိုပါ print ထုတ်ပြီး to_bool နဲ့ နှိုင်းယှဉ်ပြရမယ်
def to_int(text: str, default: int = 0) -> int:
# TODO: try int(text); on ValueError return default
...
def to_bool(text: str) -> bool:
# TODO: strip + lower, then check against ("yes", "true", "1")
...
form = {"age": " 31 ", "height_m": "1.68", "newsletter": "No", "pets": "two"}
# TODO: convert each field with the right function
# TODO: print value and type(value).__name__ for age and height
# TODO: print the newsletter flag next to bool("No")
# TODO: print next birthday as text: "Next birthday: 32"ရလဒ်: Program က အောက်ပါအတိုင်း ထုတ်ပေးရပါမယ်: age=31 (int) height=1.68 (float) newsletter=False, but bool('No') is True pets=-1 (could not read 'two') Next birthday: 32
အရိပ်အမြွက် ကြည့်ရန်
type(age).__name__ က "int" လို type နာမည်ကို string အဖြစ် ပေးပါတယ်။ pets အတွက် default=-1 ပေးလိုက်ရင် "two" ကို ဖတ်မရတာကို ရှင်းရှင်း မြင်ရပါမယ်။
အဖြေ ကြည့်ရန်
def to_int(text: str, default: int = 0) -> int:
"""Convert text to int, or return default if it is not a whole number."""
try:
return int(text)
except ValueError:
return default
def to_bool(text: str) -> bool:
"""Treat yes/true/1 (any case, extra spaces allowed) as True."""
return text.strip().lower() in ("yes", "true", "1")
form = {"age": " 31 ", "height_m": "1.68", "newsletter": "No", "pets": "two"}
age = to_int(form["age"])
height = float(form["height_m"])
newsletter = to_bool(form["newsletter"])
pets = to_int(form["pets"], default=-1)
print(f"age={age} ({type(age).__name__})")
print(f"height={height} ({type(height).__name__})")
print(f"newsletter={newsletter}, but bool('No') is {bool('No')}")
print(f"pets={pets} (could not read 'two')")
print("Next birthday: " + str(age + 1))Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- int(), float(), str(), bool() က value အသစ်ကို ပြန်ပေးလို့ variable ထဲ သိမ်းရပါတယ်။
- input() နဲ့ အပြင်က data အများစုက string ဖြစ်လို့ တွက်မချင် ပြောင်းရပါတယ်။
- int() က ကိန်းပြည့် text ကိုပဲ လက်ခံပြီး "3.5"၊ "abc" ဆိုရင် ValueError ပေးပါတယ်။
- bool() က ဗလာဟုတ်မဟုတ်ကိုပဲ စစ်လို့ "False" ဆိုတဲ့ string တောင် True ဖြစ်ပါတယ်။
The Python Tutorial — Python Software Foundation