python3中for关键字的常见用法
时间: 2024-05-09 12:21:38 浏览: 11
1. 遍历序列或集合中的元素:
```python
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
```
2. 遍历字典中的键值对:
```python
person = {'name': 'Alice', 'age': 25, 'gender': 'female'}
for key, value in person.items():
print(key, ':', value)
```
3. 遍历数字范围内的数:
```python
for i in range(1, 11):
print(i)
```
4. 遍历列表时同时获取元素下标:
```python
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, ':', fruit)
```
5. 遍历多个序列的元素:
```python
fruits = ['apple', 'banana', 'cherry']
prices = [1.2, 2.3, 3.4]
for fruit, price in zip(fruits, prices):
print(fruit, ':', price)
```
6. 循环语句中使用else:
```python
for i in range(1, 6):
print(i)
else:
print('Finished')
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)