python 循环的几种方式和实现
时间: 2024-05-01 14:21:01 浏览: 51
在 Python 中,循环有以下几种方式:
1. for 循环:for 循环可以遍历任何可迭代对象,如列表、元组、字符串、字典等等。
```python
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 遍历元组
numbers = (1, 2, 3, 4, 5)
for number in numbers:
print(number)
# 遍历字符串
text = "Hello, World!"
for char in text:
print(char)
# 遍历字典
person = {"name": "John", "age": 36, "country": "Norway"}
for key, value in person.items():
print(key, value)
```
2. while 循环:while 循环会在条件为真时重复执行代码块,直到条件为假。
```python
# 输出 0 到 4
i = 0
while i < 5:
print(i)
i += 1
```
3. range() 函数:range() 函数可以生成一个整数序列,可以在循环中使用。
```python
# 输出 0 到 4
for i in range(5):
print(i)
# 输出 2 到 6
for i in range(2, 7):
print(i)
# 输出 0 到 10,步长为 2
for i in range(0, 11, 2):
print(i)
```
4. enumerate() 函数:enumerate() 函数可以同时遍历序列的索引和值。
```python
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(i, fruit)
```
5. zip() 函数:zip() 函数可以将多个序列并排遍历。
```python
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3]
for fruit, number in zip(fruits, numbers):
print(fruit, number)
```
阅读全文