Nhập môn Python dành cho Developer
Jasmin Ludolf
Senior Data Science Content Developer
# 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
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ướcsequence = iterable, ví dụ: list, dictionary, v.v.
value = iterator, tức chỉ sối# 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
quantities = [1000, 800, 40, 30, 30, 15]
for qty in quantities:
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!")
Còn nhiều hàng
Đủ cho phần nhỏ
Sắp hết!
Sắp hết!
Sắp hết!
ingredient_name = "pasta"# Lặp qua từng ký tự for letter in ingredient_name: print(letter)
p
a
s
t
a
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)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
# 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
range(start, end + 1)
start = số bắt đầuend = số kết thúcfor i in range(1, 6):
print(i)
1
2
3
4
5
Nhập môn Python dành cho Developer