s = "Python"
for char in s:
print(char)
# 输出:
# P
# y
# t
# h
# o
# n
while condition:
# 执行操作
numbers = [1, 2, 3, 4, 5]
i = 0
while i < len(numbers):
print(numbers[i])
i += 1
# 输出:
# 1
# 2
# 3
# 4
# 5
for i in range(5):
print(i)
# 输出:
# 0
# 1
# 2
# 3
# 4
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
# 输出:
# Index: 0, Fruit: apple
# Index: 1, Fruit: banana
# Index: 2, Fruit: cherry
d = {'a': 1, 'b': 2, 'c': 3}
for key, value in d.items():
print(f"Key: {key}, Value: {value}")
# 输出:
# Key: a, Value: 1
# Key: b, Value: 2
# Key: c, Value: 3
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# 输出:
# Alice is 25 years old
# Bob is 30 years old
# Charlie is 35 years old
for i in range(10):
if i == 5:
break
print(i)
# 输出:
# 0
# 1
# 2
# 3
# 4
for i in range(5):
if i == 2:
continue
print(i)
# 输出:
# 0
# 1
# 3
# 4
for i in range(5):
print(i)
else:
print("Loop ended naturally")
# 输出:
# 0
# 1
# 2
# 3
# 4
# Loop ended naturally
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for item in row:
print(item, end=' ')
print() # 换行
# 输出:
# 1 2 3
# 4 5 6
# 7 8 9
def my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value)
# 输出:
# 1
# 2
# 3