Python中for循环的用法
时间: 2023-06-23 10:08:10 浏览: 20
Python中的for循环可以遍历任何可迭代对象,例如列表、元组、字符串、字典等等。for循环的语法如下:
```python
for variable in iterable:
# 执行代码块
```
其中,`variable` 是循环变量,`iterable` 是可迭代对象。在每次循环中,循环变量会取到可迭代对象中的下一个元素,直到可迭代对象中的所有元素都被处理完毕。
以下是一些示例:
1. 遍历列表
```python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
输出:
```
apple
banana
cherry
```
2. 遍历字符串
```python
name = "John"
for char in name:
print(char)
```
输出:
```
J
o
h
n
```
3. 遍历字典
```python
person = {"name": "John", "age": 30, "city": "New York"}
for key, value in person.items():
print(key + ": " + str(value))
```
输出:
```
name: John
age: 30
city: New York
```
4. 使用range()函数进行循环
```python
for i in range(5):
print(i)
```
输出:
```
0
1
2
3
4
```
5. 带有else的for循环
```python
for i in range(5):
print(i)
else:
print("循环结束")
```
输出:
```
0
1
2
3
4
循环结束
```
相关推荐











