Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เทคนิคการวนลูป (Looping Techniques) ใน Python


ในบทช่วยสอนนี้ เราจะเรียนรู้เกี่ยวกับเทคนิคการวนลูปใน Python 3.x หรือเวอร์ชันก่อนหน้า มีหลายวิธีที่เราสามารถนำลูปไปใช้งาน ที่นี่เราจะอภิปราย 4 เทคนิคในการลูป

โครงสร้าง Enumeration (Enumeration construct)

ตัวอย่าง

# enumerate() type
for index, value in enumerate(['Tutorial', 'point']):
    print(index, value)

ผลลัพธ์

0 Tutorial
1 point

โครงสร้าง Zip (Zip construct)

ตัวอย่าง

# zip() method
arr1 = ['Tutorial', 'point']
arr2 = ['python', 'loops']
for i, j in zip(arr1, arr2):
    print(i, j)

ผลลัพธ์

Tutorial python
point loops

โครงสร้าง Membership (Membership construct)

ตัวอย่าง

# membership operator
for i in ['Tutorial', 'point']:
    print(i)

ผลลัพธ์

Tutorial
point

โครงสร้าง Infinitive (Infinitive construct)

ตัวอย่าง

# infinite loop
while True:
    pass

โครงสร้าง Step-based (Step-based construct)

ตัวอย่าง

# range with step incrementer
for i in range(0, 4, 2):
    print(i)

ผลลัพธ์

0
2

สรุป

ในบทความนี้ เราได้เรียนรู้เกี่ยวกับ Looping Techniques ใน Python 3.x หรือเวอร์ชันก่อนหน้า