pythonfor循环怎么用
时间: 2023-11-20 13:59:07 浏览: 88
Python学习笔记之For循环用法详解
Python中的for循环可以用于迭代字符串、列表、元组、集合、字典等可迭代对象。for循环的语法格式如下:
```python
for 变量 in 可迭代对象:
循环体语句
```
其中,变量是在循环过程中每次迭代所取的值,可迭代对象是指可以返回多个值的对象,如字符串、列表、元组、集合、字典等。
以下是几个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 in thisdict:
print(x)
```
输出:
```
brand
model
year
```
4. 迭代数字
```python
for x in range(6):
print(x)
```
输出:
```
0
1
2
3
4
5
```
5. 迭代数字并指定步长
```python
for x in range(0, 10, 2):
print(x)
```
输出:
```
0
2
4
6
8
```
阅读全文