Vòng lặp for

Nhập môn Python dành cho Developer

Jasmin Ludolf

Senior Data Science Content Developer

So sánh riêng lẻ

# Số lượng nguyên liệu
quantities = [500, 400, 15, 20, 30, 5]
# Kiểm tra giá trị
quantities[0] < 10
False
quantities[1] < 10
False
Nhập môn Python dành cho Developer

Cú pháp vòng lặp for

for value in sequence:
    action
  • Với mỗi value trong sequence, thực hiện action

    • action thụt dòng do có dấu hai chấm ở dòng trước
  • sequence = iterable, ví dụ: list, dictionary, v.v.

  • value = iterator, tức chỉ số
    • Tên tạm (đặt tùy ý), thường dùng i
Nhập môn Python dành cho Developer

In từng giá trị

# Danh sách nguyên liệu
ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]


# Lặp và in từng nguyên liệu for ingredient in ingredients:
print(ingredient)
pasta
tomatoes
garlic
basil
olive oil
salt
Nhập môn Python dành cho Developer

Câu lệnh điều kiện trong vòng lặp for

quantities = [1000, 800, 40, 30, 30, 15]

for qty in quantities:
Nhập môn Python dành cho Developer

Câu lệnh điều kiện trong vòng lặp for

quantities = [1000, 800, 40, 30, 30, 15]

for qty in quantities:

# Kiểm tra nếu số lượng > 500 if qty > 500: print("Còn nhiều hàng") elif qty >= 100: print("Đủ cho phần nhỏ") else: print("Sắp hết!")
Nhập môn Python dành cho Developer

Câu lệnh điều kiện trong vòng lặp for

Còn nhiều hàng
Đủ cho phần nhỏ
Sắp hết!
Sắp hết!
Sắp hết!
Nhập môn Python dành cho Developer

Lặp qua chuỗi

ingredient_name = "pasta"

# Lặp qua từng ký tự for letter in ingredient_name: print(letter)
p
a
s
t
a
  • Hữu ích để kiểm tra văn bản, ký tự đặc biệt
Nhập môn Python dành cho Developer

Lặp qua từ điển

ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}

# Lặp qua khóa và giá trị for item, qty in ingredients.items(): print(item, ":", qty, "grams")
pasta : 500 grams
tomatoes : 400 grams
garlic : 30 grams
  • item = khóa (tên nguyên liệu)
  • qty = giá trị (số lượng)
Nhập môn Python dành cho Developer

Lặp qua từ điển

ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}
factor = 2

# Tính số lượng đã nhân for item, qty in ingredients.items(): scaled_qty = qty * factor print(item, ":", scaled_qty, "grams")
pasta : 1000 grams
tomatoes : 800 grams
garlic : 60 grams
Nhập môn Python dành cho Developer

Lặp qua từ điển

# Chỉ lặp qua khóa
for item in ingredients.keys():
    print(item)
pasta
tomatoes
garlic
# Chỉ lặp qua giá trị
for qty in ingredients.values():
    print(qty, "grams")
500 grams
400 grams
30 grams
Nhập môn Python dành cho Developer

Range

range(start, end + 1)
  • start = số bắt đầu
  • end = số kết thúc
  • Dùng để tạo hoặc biến đổi giá trị
for i in range(1, 6):
    print(i)
1
2
3
4
5
Nhập môn Python dành cho Developer

Hãy luyện tập!

Nhập môn Python dành cho Developer

Preparing Video For Download...