Control Flow (If/Else နှင့် Loops)
Program တစ်ခု ရေးတဲ့အခါ အပေါ်ကနေ အောက်ကို တစ်ကြောင်းချင်း အလုပ်လုပ်သွားတာချည်းပဲ မဟုတ်ပါဘူး။ တချို့နေရာတွေမှာ “ဒီလိုဖြစ်ရင် ဒါလုပ်မယ်” ဆိုပြီး ဆုံးဖြတ်ချက်ချတာတွေ၊ “ဒီအလုပ်ကို ၅ ခါ ထပ်လုပ်မယ်” ဆိုပြီး ခိုင်းတာတွေ လိုအပ်လာပါတယ်။ အဲ့ဒါကို Control Flow လို့ ခေါ်ပါတယ်။
Indentation (ရှေ့ကွက်လပ် ချန်ခြင်း)
Section titled “Indentation (ရှေ့ကွက်လပ် ချန်ခြင်း)”Python မှာ အရေးအကြီးဆုံး အချက်တစ်ခုက Indentation ပါ။ တခြား Language တွေမှာ {} ကို သုံးပြီး Code တွေကို အုပ်စုဖွဲ့ပေမယ့်၊ Python မှာတော့ ရှေ့ကနေ Space (ကွက်လပ်) ချန်ပြီး အုပ်စုဖွဲ့ပါတယ်။
if True: print("ဒါက if အထဲမှာ ရှိပါတယ်။") # Space ၄ ချက် ချန်ထားပါတယ်print("ဒါကတော့ အပြင်ရောက်သွားပါပြီ။")Space မချန်ရင် (သို့) အချိုးအစား မညီရင် IndentationError တက်ပါလိမ့်မယ်။
If / Elif / Else (အခြေအနေ စစ်ဆေးခြင်း)
Section titled “If / Elif / Else (အခြေအနေ စစ်ဆေးခြင်း)”အခြေအနေတစ်ခု မှန်သလား၊ မှားသလား စစ်ဆေးပြီး အလုပ်လုပ်ခိုင်းတာပါ။
age = int(input("အသက် ဘယ်လောက်လဲ? "))
if age >= 18: print("ကားမောင်းလို့ ရပါပြီ။")elif age >= 16: print("ကားမောင်းသင်လို့ ရပါပြီ။")else: print("ကားမောင်းလို့ မရသေးပါ။")Logical Operators (and, or, not)
Section titled “Logical Operators (and, or, not)”အခြေအနေ နှစ်ခု သုံးခုကို ပေါင်းစစ်ချင်တဲ့အခါ သုံးပါတယ်။
and: နှစ်ခုလုံး မှန်မှ အလုပ်လုပ်မယ်။or: တစ်ခုမှန်တာနဲ့ အလုပ်လုပ်မယ်။not: ပြောင်းပြန် လုပ်ပစ်မယ် (မှန်ရင် မှား၊ မှားရင် မှန်)။
has_ticket = Trueis_vip = False
if has_ticket and not is_vip: print("ရိုးရိုးခုံမှာ ထိုင်ပါ။")elif has_ticket or is_vip: print("VIP ခုံမှာ ထိုင်ပါ။")Loops (ထပ်ခါထပ်ခါ အလုပ်လုပ်ခြင်း)
Section titled “Loops (ထပ်ခါထပ်ခါ အလုပ်လုပ်ခြင်း)”အလုပ်တစ်ခုကို အကြိမ်ကြိမ် လုပ်ချင်တဲ့အခါ Loop တွေကို သုံးပါတယ်။
1. For Loop
Section titled “1. For Loop”အကြိမ်အရေအတွက် အတိအကျ သိတဲ့အခါ သုံးပါတယ်။ range() နဲ့ တွဲသုံးလေ့ရှိပါတယ်။
# 0 ကနေ 4 အထိ ထုတ်ပေးပါမယ် (5 မပါပါဘူး)for i in range(5): print(f"အကြိမ်အရေအတွက်: {i}")
# 1 ကနေ 10 အထိ၊ 2 ခြားပြီး သွားမယ် (1, 3, 5, 7, 9)for i in range(1, 10, 2): print(i)2. While Loop
Section titled “2. While Loop”အခြေအနေတစ်ခု မှန်နေသရွေ့ ဆက်လုပ်ချင်တဲ့အခါ သုံးပါတယ်။
count = 1
while count <= 3: print(f"Hello {count}") count = count + 1 # ဒါမပါရင် အဆုံးမရှိ (Infinite Loop) ဖြစ်သွားပါမယ်Break နှင့် Continue
Section titled “Break နှင့် Continue”Loop တွေ အလုပ်လုပ်နေတုန်းမှာ ကြားဖြတ်ပြီး ရပ်ချင်တာ၊ ကျော်သွားချင်တာတွေ လုပ်လို့ရပါတယ်။
break: Loop ကြီး တစ်ခုလုံးကို ရပ်ပစ်လိုက်ပါတယ်။continue: အခု လက်ရှိ အကြိမ်ကို ကျော်ပြီး နောက်တစ်ကြိမ်ကို ဆက်သွားပါတယ်။
# Break ဥပမာfor i in range(10): if i == 5: break # 5 ရောက်တာနဲ့ Loop ကြီး ရပ်သွားမယ် print(i) # 0, 1, 2, 3, 4 ပဲ ထွက်ပါမယ်
# Continue ဥပမာfor i in range(5): if i == 2: continue # 2 ကို ကျော်သွားမယ် print(i) # 0, 1, 3, 4 ပဲ ထွက်ပါမယ်