pyhon for循环
时间: 2023-07-17 20:06:38 浏览: 44
Python 中的 for 循环用于遍历可迭代对象(如列表、元组、字符串等)中的元素。下面是一些常见的 for 循环的用法示例:
1. 遍历列表:
```python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
2. 遍历字符串:
```python
message = "Hello, World!"
for char in message:
print(char)
```
3. 遍历字典的键:
```python
student = {"name": "Alice", "age": 20, "grade": "A"}
for key in student:
print(key)
```
4. 遍历字典的值:
```python
student = {"name": "Alice", "age": 20, "grade": "A"}
for value in student.values():
print(value)
```
5. 遍历字典的键值对:
```python
student = {"name": "Alice", "age": 20, "grade": "A"}
for key, value in student.items():
print(key, value)
```
6. 使用 range() 函数进行指定次数的循环:
```python
for i in range(5):
print(i)
```
以上是一些常见的 for 循环的用法示例,你可以根据自己的需要进行调整和扩展。
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)