Python ရှိ Ternary Operator
ကျွန်ုပ်တို့တွင် variable နှစ်ခုရှိသည်ဆိုပါစို့။
tst1 = 5
tst2 = 10
ဘယ်ဟာက ပိုကြီးသလဲဆိုတာ စစ်ဆေးကြည့်ပြီး သက်ဆိုင်ရာ မက်ဆေ့ဂျ်ကို ထုတ်ပြကြရအောင်။
if tst1 > tst2:
print('+++')
else:
print('---')
သို့သော် ဤအခြေအနေကို ternary operator ဖြင့် ပိုတိုတောင်းသော ပုံစံဖြင့် ရေးသားနိုင်ပါသည်။
၎င်း၏ syntax သည် ဤသို့ဖြစ်သည်။
'message if condition 1 is true' if condition else 'message if condition 1 is false'
Ternary operator ဖြင့် အခြေအနေကို ပြန်ရေးကြည့်ကြရအောင်။
print('+++' if tst1 > tst2 else '---')
Ternary operator ကို အလွန်ရိုးရှင်းသောကိစ္စများတွင်သာ အသုံးပြုသင့်သည်။ အဘယ်ကြောင့်ဆိုသော် ၎င်း၏အသုံးပြုမှုသည် code ကို နားလည်ရန် ခက်ခဲစေသောကြောင့်ဖြစ်သည်။
အောက်ပါ code ကို ပေးထားသည်။
tst = 12
if tst > 0:
print('+++')
else:
print('---')
Ternary operator ကိုသုံးပြီး ပြန်ရေးပါ။
အောက်ပါ code ကို ပေးထားသည်။
tst = 'abcde'
if 'a' in tst:
print('+++')
else:
print('---')
Ternary operator ကိုသုံးပြီး ပြန်ရေးပါ။