python的for循环代码
时间: 2023-12-03 07:39:25 浏览: 73
Python中的for循环可以用于遍历序列(如列表、元组或字符串)中的元素,也可以用于遍历字典中的键值对。下面是几个for循环的例子:
1. 遍历列表中的元素
```python
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
```
输出:
```
apple
banana
cherry
```
2. 遍历字符串中的字符
```python
for x in "banana":
print(x)
```
输出:
```
b
a
n
a
n
a
```
3. 遍历字典中的键值对
```python
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
for x, y in thisdict.items():
print(x, y)
```
输出:
```
brand Ford
model Mustang
year 1964
```
阅读全文