for element in iterable:
statement(s)
element:是循环变量,用于存储可迭代对象中当前遍历到的元素。
iterable:是需要遍历的可迭代对象,如列表、元组、字典等。
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
word = "Python"
for char in word:
print(char)
P
y
t
h
o
n
numbers = (1, 2, 3, 4, 5)
for num in numbers:
print(num * 2)
2
4
6
8
10
colors = {"red", "green", "blue"}
for color in colors:
print(color)
red
green
blue
person = {"name": "Alice", "age": 25, "city": "New York"}
for key, value in person.items():
print(f"Key: {key}, Value: {value}")
Key: name, Value: Alice
Key: age, Value: 25
Key: city, Value: New York
person = {"name": "Alice", "age": 25, "city": "New York"}
for key in person.keys():
print(f"Key: {key}, Value: {person[key]}")
Key: name, Value: Alice
Key: age, Value: 25
Key: city, Value: New York
person = {"name": "Alice", "age": 25, "city": "New York"}
for key in person:
print(key, ":", person[key])
name : Alice
age : 25
city : New York
person = {"name": "Alice", "age": 25, "city": "New York"}
for value in person.values():
print(f"Value: {value}")
Value: Alice
Value: 25
Value: New York
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
break 语句:用于提前终止循环
for num in range(10):
if num == 5:
break
print(num)
0
1
2
3
4
continue 语句:用于跳过当前循环的剩余代码,直接进入下一次循环
for num in range(10):
if num % 2 == 0:
continue
print(num)
1
3
5
7
9
range() 函数用于生成一个整数序列,通常用于循环中,尤其是 for 循环。它是一个非常灵活且高效的工具,可以生成不同形式的整数序列。
基本语法
参数说明
for i in range(5):
print(i)
运行结果:
0
1
2
3
4
for i in range(2, 7):
print(i)
2
3
4
5
6
正步长:
for i in range(1, 10, 2):
print(i)
1
3
5
7
9
负步长:
for i in range(10, 0, -1):
print(i)
10
9
8
7
6
5
4
3
2
1