while និង for គឺជា statement ដែលតំរូវអោយអនុវត្ត block នៃ statement សារចុះសារឡើង ជាច្រើនលើកច្រើនសារ គឺប្រៀបបាននទៅនឹងកងចក្រមួយដែលវិលគ្មានឈប់។ សកម្មភាពវិលជាប់ ត្រូវហៅថា loop ។
ក្រៅពីការបង្កើត loop តែមួយ យើងក៏អាចបង្កើត loop មួយនៅក្នុង loop មួយទៀតបានដែរ ដោយធ្វើដូចខាងក្រោមនេះ៖1 2 3 4 5 6 7 8 9 10 11 12 13 | int_list = [ 10 , 20 , 30 , 40 , 50 ] real_list = [ 1.5 , 2.33 , 3.17 , 4.32 ] index = 0 for x in int_list: print ( 'The element in int_list having index' , index, 'is' , x) number = 0 for y in real_list: print ( 'The element in real_list having index' , number, 'is' , y) number + = 1 index + = 1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | The element in int_list having index 0 is 10 The element in real_list having index 0 is 1.5 The element in real_list having index 0 is 2.33 The element in real_list having index 0 is 3.17 The element in real_list having index 0 is 4.32 The element in int_list having index 1 is 20 The element in real_list having index 0 is 1.5 The element in real_list having index 0 is 2.33 The element in real_list having index 0 is 3.17 The element in real_list having index 0 is 4.32 The element in int_list having index 2 is 30 The element in real_list having index 0 is 1.5 The element in real_list having index 0 is 2.33 The element in real_list having index 0 is 3.17 The element in real_list having index 0 is 4.32 The element in int_list having index 3 is 40 The element in real_list having index 0 is 1.5 The element in real_list having index 0 is 2.33 The element in real_list having index 0 is 3.17 The element in real_list having index 0 is 4.32 The element in int_list having index 4 is 50 The element in real_list having index 0 is 1.5 The element in real_list having index 0 is 2.33 The element in real_list having index 0 is 3.17 The element in real_list having index 0 is 4.32 |
ក្នុងករណីមាន loop មួយនៅក្នុង loop មួយទៀត ដែលភាសាអង់គ្លេសហៅថា nested loop, block នៃ statement ដែលជា loop នៅខាងក្នុង ត្រូវយកទៅអនុវត្តរហូតដល់លក្ខខ័ណ្ឌត្រូវបំពេញ រាល់លើកដែល block នៃ statement ដែលជា loop នៅខាងក្រៅត្រូវយកទៅអនុវត្តម្តង។ ជាក់ស្តែង នៅក្នុងកម្មវិធីខាងលើនេះ រាល់លើកដែល element នៃកំរង list ឈ្មោះ int_list ត្រូវយកមកពិនិត្យ និង block នៃ statement នៅក្នុង statement for ដែលជា loop នៅខាងក្រៅត្រូវយកទៅអនុវត្តម្តង block នៃ statement នៅក្នុង statement for ដែលជា loop នៅខាងក្នុង ត្រូវយកទៅអនុវត្តជាច្រើនលើកច្រើនសារ រហូតដល់ element នៃកំរង list ឈ្មោះ real_list ត្រូវត្រួតពិនិត្យបានអស់សព្វគ្រប់៕