Python For Loops

ကုဒ်အစုအဝေး(block of code)တစ်ခုကို အကြိမ်ကြိမ် အထပ်ထပ်(repetitive) execute လုပ်လိုသည့်အခါ for loop ကို အသုံးပြုသည်။ For loop ကို စုစုပေါင်းတန်ဖိုး(sum)၊ ပျှမ်းမျှတန်ဖိုး(average)စသည့် aggregate များကို တွက်ရန် သုံးသည်။

ကုဒ်အစုအဝေး(block of code)တစ်ခုကို အကြိမ်ကြိမ် အထပ်ထပ်(repetitive) execution လုပ်နေခြင်းကို iteration ဟုခေါ်သည်။ လုပ်ရမည့် အကြိမ်အရေအတွက် အတိအကျ ရှိလျှင် definite iteration ဖြစ်သည်။ လုပ်ရမည့် အကြိမ်အရေအတွက် အတိအကျ မရှိလျှင် indefinite iteration ဖြစ်သည်။
Definite iteration သည် for loop ဖြစ်သည်။
Indefinite iteration သည် while loop ဖြစ်သည်။ ထို့ကြောင့် python တွင် For loop နှင့် while loop ဟူ၍ (၂)မျိုးရှိသည်။
For loop သည် definite iteration loop ဖြစ်သည်။ Loop ပတ်ရမည် အကြိမ်အရေအတွက် အတိအကျ သတ်သတ်မှတ်မှတ်ရှိသည့် loop ဖြစ်သည်။

while loop တွင် loop ပတ်ရမည် အကြိမ်အရေအတွက် အတိအကျ မရှိသောကြောင့် Indefinite iteration ဟုခေါ်ခြင်းဖြစ်သည်။ while loop သည် အလိုရှိသည့် အခြေအနေတစ်ခုသို့ ရောက်သည့်တိုင်အောင် loop ကို ပတ်နေရမည်ဖြစ်သောကြောင့် အရေအတွက် အတိအကျ ပြောရန် မဖြစ်နိုင်ပါ။ (indefinite iteration ဖြစ်သည်)

Collection-Based or Iterator-Based Loop (For Loop)

Loop တစ်ကြိမ်ပတ်တိုင်း variable(i)ဖြင့် အစုအဝေးတစ်ခု(a collection of objects)ထဲမှ itemများ တစ်ခုချင်းစီကို ထုတ်ယူပြီး loop အတွင်းသို့ထည့်က ဆောင်ရွက်ရမည့် ကိစ္စများကို ဆောင်ရွက်စေခြင်းကို Collection-Based Loop သို့မဟုတ် Iterator-Based Loop ဟု ခေါ်သည်။

Python for loop ၏ syntax ကို အတိုင်း ရေးသည်။ for keyword ၏ နောက်တွင် variable (i) လိုက်သည်။ ၎င်းနောက်တွင် in keyword လိုက်သည်။ နောက်ဆုံးတွင် <iterable> item များရှိသည်။

In [1]:
for <var> in <iterable>:
    <statement(s)>
  File "<ipython-input-1-a715cbfa304b>", line 1
    for <var> in <iterable>:
        ^
SyntaxError: invalid syntax

<iterable>သည် object များ အစုအဝေး ဖြစ်သည်။(<iterable> is a collection of objects)။ ဥပမာ list တစ်ခု ဖြစ်နိုင်သလို tuple တစ်ခုလည်း ဖြစ်နိုင်သည်။ loop body အတွင်းရှိ <statement(s)> ကို indentation ဖြင့် ရေးရမည်။ Python control structures အရ ထဲမှာ item တစ်ခုချင်းစီကို execute လုပ်သည်။ ဥပမာ i = 1 အတွက် execute လုပ်သည်။ ထို့နောက် i = 2 အတွက် execute လုပ်သည်။ သတ်မှတ်ထားသည့် အရေအတွက် ရောက်သည့်တိုင်အောင် execute လုပ်သည်။

In [2]:
for i in <collection>
    <loop body>
  File "<ipython-input-2-5a4dfde3708a>", line 1
    for i in <collection>
             ^
SyntaxError: invalid syntax

Iterables

Python တွင် iterable ၏ အဓိပ္ပာယ်မှာ iteration လုပ်နိုင်သည့် object များကို ဖြစ်သည်။ (means an object can be used in iteration) object တစ်ခုသည် iterable ဖြစ်လျှင် built-in Python function iter() ထဲသို့ ထည့်ပေးနိုင်သည်။ String , List, Tuple, Set, Dict စသည့် data type များသည် iterable ဖြစ်သည်။

In [3]:
# String 
iter("python") # String
Out[3]:
<str_iterator at 0x208d9926088>
In [4]:
iter(('red', 'green', 'blue', 'yellow')) #Tuple
Out[4]:
<tuple_iterator at 0x208d99009c8>
In [5]:
 iter(['red', 'green', 'blue', 'yellow']) # List
Out[5]:
<list_iterator at 0x208d98e8148>
In [6]:
iter({'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}) # Dict
Out[6]:
<dict_keyiterator at 0x208d9919228>
In [7]:
iter({'red', 'green', 'blue', 'yellow'}) #set
Out[7]:
<set_iterator at 0x208d98ea0e8>

အောက်ပါတို့သည့် iterable မဟုတ်သည့် သို့မဟုတ် iterable မဖြစ်သည့် object များ ဖြစ်ကြသည်။

In [8]:
iter(42) # Integer သည် Iterable မဟုတ်သောကြောင့် TypeError ပေးလိမ့်မည်။
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-5e608e3277d3> in <module>
----> 1 iter(42) # Integer သည် Iterable မဟုတ်သောကြောင့် TypeError ပေးလိမ့်မည်။

TypeError: 'int' object is not iterable
In [9]:
iter(3.1) # Float သည် Iterable မဟုတ်သောကြောင့် TypeError ပေးလိမ့်မည်။
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-564f0e4463dc> in <module>
----> 1 iter(3.1) # Float သည် Iterable မဟုတ်သောကြောင့် TypeError ပေးလိမ့်မည်။

TypeError: 'float' object is not iterable
In [10]:
iter(len) # lenသည် Iterable မဟုတ်သောကြောင့် TypeError ပေးလိမ့်မည်။  
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-4dd85a4f5616> in <module>
----> 1 iter(len) # lenသည် Iterable မဟုတ်သောကြောင့် TypeError ပေးလိမ့်မည်။

TypeError: 'builtin_function_or_method' object is not iterable

အတိုချုပ်အားဖြင့် collection သို့မဟုတ် container အမျိုးအစား(type) များဖြစ်ကြသည့် string, list, tuple, dict, set, နှင့် frozenset တို့သည် iterable များ ဖြစ်ကြသည်။ loop ပတ်နိုင်သည့် data type များဖြစ်ကြသည်။

range() function

range built-in function ကို for loop နှင့် တွဲ၍ အလွန်အသုံးများသည်။ Iterate လုပ်နိုင်သည့် ကိန်းအစဥ်အတန်း(sequence of integers)ကို အလိုရှိသည့်အခါ built-in range() function ကို သုံးနိုင်သည်။ range() ထုတ်ပေးသည့်အရာမှ object of class range တစ်ခုသာဖြစ်သည်။ list တစ်ခု သို့မဟုတ် tuple မဟုတ်ပါ။ range object ကို iterate လုပ်နိုင်သည်။

In [11]:
for number in range(3):
    print(number)
0
1
2

range([start], stop, [step]) start သည် စဆုံး item ဖြစ်သည်။ stop သည် အဆုံး item ဖြစ်သည်။ သို့သော်ထို အဆုံးကိန်း မပါဝင်ပါ။ step သည် အစနှင့် အဆုံး အကြား item မည်မျှကို ကျော်ရမည်ကို ဖော်ပြသည်။

  • start: အစဆုံးကိန်း(starting number of the sequence)
  • stop: အဆုံးကိန်း မတိုင်ခင်ကိန်း(generate numbers up to but not including this number)
  • step: This is the difference between each number in the sequence.

    square brackets [ ] ထဲထည့်ရေးထားသည့် start နှင့် step သည် လိုအပ်သည့်အခါမှသာ ထည့်ပေးရန်လိုသည်။

In [12]:
for number in range(0, 8, 2):  # last one is step
    print(number)
0
2
4
6
In [13]:
total = 0
for number in range(8):
    total += number
print(total)
28

Looping over a collection

Len() ဖြင့် item အများ၏ အရေအတွက် ရှာပြီး range() function ထဲထည့်၍ loop ပတ်နိုင်သည်။ Len() နှင့် range()ကို မသုံးဘဲ for color in colors code တွင် colors ဆိုသည့် list ထဲမှ color item တစ်ခုချင်းစီ ကို ခေါ်ပြီး loop ပတ်နိုင်သည်။

In [14]:
colors = ['red', 'green', 'blue']
for i in range(len(colors)):
    print (colors[i])
red
green
blue
In [15]:
#  colors ဆိုသည့် list ထဲမှ color item တစ်ခုချင်းစီ ကို ခေါ်ပြီး loop ပတ်နိုင်သည်။ 
for color in colors:
    print(color)
red
green
blue

Loop ကို ပြောင်းပြန်ပတ်ခြင်း(Looping backwards) Len() နှင့် range()ကို သုံး၍ start: -1, end:-1, step:-1 ပေး၍ Loop ကို ပြောင်းပြန်ပတ်နိုင်သည်။ reversed() ကို သုံး၍ Loop ကို ပြောင်းပြန်ပတ်နိုင်သည်။

In [16]:
colors = ['red', 'green', 'blue']

for i in range(len(colors)-1, -1, -1):
    print(colors[i])
blue
green
red
In [17]:
# reversed() ကို သုံး၍ Loop ကို ပြောင်းပြန်ပတ်နိုင်သည်။
for color in reversed(colors):
    print(color)
blue
green
red

Item များနှင့် index နံပါတ်များကို တွဲ၍ ဖော်ပြရန် loop ပတ်ခြင်း(Looping over a collection and indices)

In [18]:
colors = ['red', 'green', 'blue', 'yellow']
for i in range(len(colors)):
    print (i, '--->', colors[i])
0 ---> red
1 ---> green
2 ---> blue
3 ---> yellow
In [19]:
for i, color in enumerate(colors):
    print(i, '--->', color)
0 ---> red
1 ---> green
2 ---> blue
3 ---> yellow

Looping over two collections collection နှစ်ခု သို့မဟုတ် list နှစ်ခုကို အတွဲဖြစ်အောင် loop ပတ်သည့်အခါ အရေအတွက်အနည်းဆုံး ရှိသည့် collection သို့မဟုတ် list အထိသာ ရသည်။ ထို့ကြောင့် min() ကို အသုံးပြုထားသည်။ min(len(names), len(colors)) တွင် အနည်းဆုံးအရေအတွက်သည် loop ပတ်ရမည့် အကြိမ် အရေအတွက် ဖြစ်သည်။

In [20]:
names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue', 'yellow']
n = min(len(names), len(colors))
for i in range(n):
    print(names[i], '--->', colors[i])
raymond ---> red
rachel ---> green
matthew ---> blue

parallel iteration လုပ်ရန်အတွက် zip() function ကို အသုံးပြုထားသည်။

In [21]:
for name, color in zip(names, colors):
    print(name, '--->', color)
raymond ---> red
rachel ---> green
matthew ---> blue

Looping in sorted order ငယ်ရာမှ ကြီးရာ ၊ စာလုံးရေ အနည်းမှာ များရာသို့ စသည်ဖြင့် စီထားပြီး(sorted)သားဖြစ်အောင် loop ပတ်ခြင်း

In [22]:
colors = ['red', 'green', 'blue', 'yellow']
# Forward sorted order
for color in sorted(colors):
    print(colors)
['red', 'green', 'blue', 'yellow']
['red', 'green', 'blue', 'yellow']
['red', 'green', 'blue', 'yellow']
['red', 'green', 'blue', 'yellow']
In [23]:
# Backwards sorted order
for color in sorted(colors, reverse=True):
    print(colors)
['red', 'green', 'blue', 'yellow']
['red', 'green', 'blue', 'yellow']
['red', 'green', 'blue', 'yellow']
['red', 'green', 'blue', 'yellow']

မိမိအလိုရှိသည့် အတိုင်းဖြင်အောင် စီခြင်း(Custom Sort Order)

In [24]:
colors = ['red', 'green', 'blue', 'yellow']

def compare_length(c1, c2):
    if len(c1) < len(c2): return -1
    if len(c1) > len(c2): return 1
    return 0

#print(sorted(colors, cmp=compare_length))
print(sorted(colors, key = len))
['red', 'blue', 'green', 'yellow']

dictionary key များဖြင့် loop ပတ်ခြင်း(Looping over dictionary keys)

In [25]:
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
for k in d:
    print(k)
matthew
rachel
raymond
In [26]:
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
for k in d.keys():
    print(k)
matthew
rachel
raymond

Looping over dictionary keys and values

In [27]:
# Not very fast, has to re-hash every key and do a lookup
for k in d:
    print(k, '--->', d[k])
matthew ---> blue
rachel ---> green
raymond ---> red
In [28]:
# Makes a big huge list
for k, v in d.items():
    print(k, '--->', v)
matthew ---> blue
rachel ---> green
raymond ---> red

Looping Over Multiple Iterables

တစ်ခုထက်ပိုများသည့် iterable collection များဖြစ်သော lists, tuples တို့ကို looping လုပ်သည့်အခါ zip() function ကို အသုံးပြုသည်။ zip() ကို အသုံးပြု၍ တစ်ခုထက်ပိုများသည့် lists, tuples တို့ကို မည်ကဲ့သို့ looping လုပ်သည်ကို အောက်တွင် ရှင်းပြထားသည်။

Traversing Lists in Parallel Python’s zip() function allows you to iterate in parallel over two or more iterables. Since zip() generates tuples, you can unpack these in the header of a for loop:

In [29]:
letters = ['a', 'b', 'c']
numbers = [0, 1, 2]
special_char = ['@', '$', '!']
for l, n, sc in zip(letters, numbers, special_char):
    print(f'Letter: {l} Number: {n} Special Character: {sc}') 
Letter: a Number: 0 Special Character: @
Letter: b Number: 1 Special Character: $
Letter: c Number: 2 Special Character: !

l, n, sc in zip(letters, numbers, special_char) တွင် letters ဟုသည့် list ထဲမှ l ဖြင့် item များကို ထုတ်ယူသည်, numbers ဟုသည့် list ထဲမှ n ဖြင့် item များကို ထုတ်ယူသည်, special_char ဟုသည့် list ထဲမှ sc ဖြင့် item များကို ထုတ်ယူသည်။ zip() ဖြင့် တွဲသည်။ (combine လုပ်သည်။)

In [30]:
# အောက်တွင် list (၄)ခုကို loop တစ်ခုတည်းဖြင့် တွဲနိုင်ပုံကို ဖော်ပြထားသည်။ 
letters = ['a', 'b', 'c']
numbers = [0, 1, 2]
special_char = ['@', '$', '!']
operators = ['*', '/', '+']
for l, n, sc, o in zip(letters, numbers, special_char, operators):
    print(f'Letter: {l} Number: {n} Special Character: {sc} Operator: {o}') 
Letter: a Number: 0 Special Character: @ Operator: *
Letter: b Number: 1 Special Character: $ Operator: /
Letter: c Number: 2 Special Character: ! Operator: +

For loop ကိုသုံး၍ dictionary အတွင်းရှိ item များကို ရေတွက်ခြင်း

In [31]:
colors = ['red', 'green', 'red', 'blue', 'green', 'red']

# Simple, basic way to count. A good start for beginners.
d = {}
for color in colors:
    if color not in d:
        d[color] = 0
    d[color] += 1
        
print(d) # {'blue': 1, 'green': 2, 'red': 3}
{'red': 3, 'green': 2, 'blue': 1}
In [32]:
# pythonic code
d = {}
for color in colors:
    d[color] = d.get(color, 0) + 1  
print(d) 
{'red': 3, 'green': 2, 'blue': 1}

နာမည်စာလုံး၏ အက္ခရာအလုံးရေကိုလိုက်၍ group ဖွဲ့ခြင်း(Grouping with dictionaries)

In [33]:
names = ['raymond', 'rachel', 'matthew', 'roger',
         'betty', 'melissa', 'judith', 'charlie']

# In this example, we're grouping by name length
d = {}
for name in names:
    key = len(name)  # နာမည်စာလုံးမှ အက္ခရာအလုံးရေကို တွက်သည်။
    if key not in d: # အက္ခရာအလုံးအရေအတွက်သည် d ထဲတွင် မရှိလျှင် ထည့်ရန်
        d[key] = []  
    d[key].append(name)
    
d
Out[33]:
{7: ['raymond', 'matthew', 'melissa', 'charlie'],
 6: ['rachel', 'judith'],
 5: ['roger', 'betty']}

String များကို ပေါင်းစပ်(concatenate)ရန် အတွက်လည်း သုံးသည်။

In [34]:
names = ['raymond', 'rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie']

s = names[0]
for name in names[1:]:
    s += ', ' + name
print(s)
print(names)
raymond, rachel, matthew, roger, betty, melissa, judith, charlie
['raymond', 'rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie']

Sequence များကို update လုပ်ရန်အတွက်လည်းသုံးသည်။

In [35]:
result = []
for i in range(10):
    s = i ** 2
    result.append(s)
print(sum(result))
285

Looping lists

In [36]:
my_list = [1, 2, 3, 4, 'Python', 'is', 'neat']
for item in my_list:
    print(item)
1
2
3
4
Python
is
neat

enumerate()

In case you need to also know the index:

In [37]:
for idx, val in enumerate(my_list):
    print('idx: {}, value: {}'.format(idx, val))
idx: 0, value: 1
idx: 1, value: 2
idx: 2, value: 3
idx: 3, value: 4
idx: 4, value: Python
idx: 5, value: is
idx: 6, value: neat

Looping dictionaries

In [38]:
my_dict = {'hacker': True, 'age': 72, 'name': 'John Doe'}
for val in my_dict:
    print(val)
hacker
age
name
In [39]:
for key, val in my_dict.items():
    print('{}={}'.format(key, val))
hacker=True
age=72
name=John Doe

သုညမှ (၉) အထိ ကိန်း (၁၀)လုံးမှ အစဥလိုက် ကိန်း(၅)လုံးစီပါသည့် list နှစ်ခု တည်ဆောက်ပါ။
Empty list နှစ်ခုတည်ဆောက်သည်။ range(10)ကို for loop ပတ်သည်။ အလယ်ကိန်း(midpoint) ၅ထက် ငယ်လျှင် lower ဆိုသည့် list ထည့်သည်။ ကြီးလျှင် upper ဆိုသည့် list ထဲထည့်သည်။

In [40]:
# set the midpoint
midpoint = 5

# make two empty lists
lower = []; upper = []

# split the numbers into lower and upper
for i in range(10):
    if (i < midpoint):
        lower.append(i)
    else:
        upper.append(i)
        
print("lower:", lower)
print("upper:", upper)
lower: [0, 1, 2, 3, 4]
upper: [5, 6, 7, 8, 9]

Breaking Out of Loops (break , continue and pass)

Loop များအတွက် statement (၃)ခုမှာ

  • break statement
  • continue statement နှင့်
  • pass statement တို့ဖြစ်သည်။

Break statement နှင့် continue statement

Break statement နှင့် continue statement တို့ကို သုံး၍ loop ပတ်ပုံ(loop behavior)ကို ပြောင်းနိုင်သည်။ Break statement ကို သုံး၍ while loop တွင် ရပ်တန့်သကဲ့သို့ loop တွင်းလည်း ရပ်တန့်ပစ်နိုင်သည်။ တစ်နည်းအားဖြင့် loop အတွင်းမှ exit လုပ်သည်။ Continue statement ကို သုံး၍ while loop တွင် ကျော်သွားသကဲ့သို့ loop တွင်းလည်း next iteration သို့ကျော်သွားနိုင်သည်။

break: Jumps out of the closest enclosing loop (past the entire loop statement)

In [41]:
#Stop the execution of the loop.
my_list = [1, 2, 3, 4, 'Python', 'is', 'neat']
for item in my_list:
    if item == 4:
        break
    print(item)
1
2
3
In [42]:
for i in ['green', 'yellow', 'blue', 'pink']:
    if 'blue' in i: # 'blue' ရောက်သည့်အချိန်တွင် loop ရပ်သွားလိမ့်မည်။
        break
    print(i)  
green
yellow

Continue statement ကို လက်ရှိပတ်နေသည့် loop ကို ရပ်ပစ်ပြီး နောက်လာမည့် item အတွက် ဆက်(continue)ပတ်လိုသည့်အခါတွင် သုံးသည်။ (continue statement terminates the current iteration and proceeds to the next iteration)။ အောက်ဥပမာတွင် 'blue' သည်အခါ loop ကို ရပ်ပစ်ပြီး ပြန်စသည့်အတွက် 'blue' မပါတော့ပေ။
continue: Jumps to the top of the closest enclosing loop (to the loop’s header line)

In [43]:
for i in ['green', 'yellow', 'blue', 'pink']:
    if 'blue' in i: # 'blue' ရောက်သည့်အချိန်တွင် loop ရပ်သွားလိမ့်မည်။
        continue
    print(i)  
green
yellow
pink
In [44]:
# Continue to the next item without executing the lines 
# occuring after `continue` inside the loop.
for item in my_list:
    if item == 1:
        continue
    print(item)
2
3
4
Python
is
neat

pass Statement

ပြင်ပအခြေအနေတစ်ခုခုမှ loop ရပ်တန့်ရမည့်အခါ pass statement ကို ထည့်ထားခြင်းဖြင့် loop ပုံမှန် ဆက်ပတ်နိုင်သည်။ ကုဒ်များ ပြီးဆုံးသည်အထိ ဆက် run နိုင်သည်။ pass statement ကို conditional if statement နှင့် တွဲသုံးလေ့ရှိသည်။
pass: Does nothing at all: it’s an empty statement placeholder

In [45]:
# Loop over all numbers from 1 to 10 
for number in range(1,5):  
    # If the number is 4, proceed as normal  
    if number == 2:    
        pass
    print(number)
1
2
3
4

For loop နှင့် else clause တွဲသုံးနိုင်သည်။

Iterable item များ မရှိတော့၍ loop အဆုံးသတ်(terminate)သည့်အခါ else clause သည် စတင် အလုပ် လုပ်လိမ့်မည်။ loop တစ်ခုသည် ပြီးဆုံးသည် သို့မဟုတ် မပြီးခင် ရပ်တန့်သွားသည် သိရန်တွက် for loop တွင် else clause ကို ထည့်သုံးသည်။
Loop else block: Runs if and only if the loop is exited normally (i.e., without hitting a break)

In [46]:
for i in ['green', 'yellow', 'blue', 'pink']:
    print(i)
else:
    print('Done.')  # Will execute
green
yellow
blue
pink
Done.

Break statement ကြောင့် သည် အဆုံးထိ ရောက်အောင် ပတ်ခွင့် မရဘဲ ရပ်တန့်သွားလျှင် else clause သည် အလုပ်လုပ်လိမ့်မည် မဟုတ်ပေ။ (The else clause won’t be executed if the list is broken out of with a break statement) အောက်တွင် ဥပမာဖြင့် ပြထားသည်။

In [47]:
for i in ['green', 'yellow', 'blue', 'pink']:
    if i == 'blue':
        break
    print(i)
else:
    print('Done.')  # blue ရောက်သည့်အခါ break ဖြစ်သွားပြီး loop ရပ် သွားသည်။ 
green
yellow

Nested Loops

အောက်က ကုဒ်ကို ရင် ငယ်ငယ်တုန်းက ကျက်ခဲ့ရတဲ့ အလီစာရွက်ကလေးကို သတိရလိမ့်မည်။

In [ ]:
for i in range(1,13):
    for j in range(1,13):
        print(f'{i} x {j} = {i*j}')
    print("--------------")

-End-