วนซ้ำด้วย `for`

Basic python

วนซ้ำด้วย `for`

for ใช้เดินทางไปตามรายการและทำงานซ้ำทีละองค์ประกอบ

fruits = ["りんご", "みかん", "ぶどう"]
for fruit in fruits:
    print(fruit)

ฟังก์ชัน range #

range() สร้างเลขลำดับ

for i in range(5):
    print(i)      # 0..4

for i in range(1, 6):
    print(i)      # 1..5

for i in range(0, 10, 2):
    print(i)      # เลขคู่

enumerate และ zip #

ใช้ enumerate() เมื่ออยากได้ index กับค่าไปพร้อมกัน

for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

ถ้าต้องการเดินพร้อมกันหลายลิสต์ ใช้ zip()

names = ["Alice", "Bob", "Carol"]
ages = [24, 32, 28]

for name, age in zip(names, ages):
    print(f"{name} อายุ {age}")

ลองทำดู #

  1. พิมพ์เลข 1 ถึง 100 โดยเลขหารด้วย 3 ลงตัวให้แสดง “Fizz”, หารด้วย 5 ลงตัวแสดง “Buzz”, หารได้ทั้งสองแสดง “FizzBuzz”
  2. สร้างลิสต์คำที่ชอบ แล้วใช้ for แปลงแต่ละคำเป็นตัวพิมพ์ใหญ่ก่อนพิมพ์