admin 管理员组

文章数量: 1184232


2023年12月23日发(作者:python中的断言)

python中for循环的用法

Python是一种高级编程语言,应用广泛,其中for循环是Python重要的语法结构之一。for循环是循环控制结构的一种,用于遍历序列(比如列表、元组或字符串)或其他可迭代的对象,执行内嵌语句。下面将详细介绍Python中for循环的用法。

基本语法

Python中for循环的基本语法如下:

```python

for 变量 in 序列:

执行语句块

```

其中,变量是在循环过程中取出的序列中的每一个元素,序列可以是列表、元组、字符串等;执行语句块是需要循环执行的代码块。

应用举例

1. 遍历列表

遍历列表中每一个元素,输出其值。

```python

fruits = ['banana', 'apple', 'mango']

for fruit in fruits:

print("I like", fruit)

```

输出结果:

```

I like banana

I like apple

I like mango

```

2. 遍历字符串

遍历字符串中每一个字符,输出其 Unicode 码点。

```python

string = "Python"

for char in string:

print(char, ord(char))

```

输出结果:

```

P 80

y 121

t 116

h 104

o 111

n 110

```

3. 遍历元组

遍历元组中每一个元素,输出其值。

```python

numbers = (5, 10, 15, 20)

for num in numbers:

print(num, "is a multiple of 5")

```

输出结果:

```

5 is a multiple of 5

10 is a multiple of 5

15 is a multiple of 5

20 is a multiple of 5

```

4. 遍历字典

遍历字典中每一个键值对,输出其键和值。

```python

person = {'name': 'Alice', 'age': 23, 'gender': 'female'}

for key, value in ():

print(key, ":", value)

```

输出结果:

```

name : Alice

age : 23

gender : female

```

range()函数

Python中内置的range()函数可以按照指定的范围生成一个整数序列,默认情况下从0开始,步长为1。range()函数的格式如下:

```python

range(start, stop, step)

```

其中,start是起始值,默认为0;stop是终止值,必填,但取不到;step是步长,默认为1。

应用举例

1. 输出1~10内的所有整数。

```python

for i in range(1, 11):

print(i)

```

输出结果:

```

1

2

3

4

5

6

7

8

9

10

```

2. 输出1~10内的所有偶数。

```python

for num in range(2, 11, 2):

print(num)

```

输出结果:

```

2

4

6

8

10

```

循环嵌套

在Python中,可以将一个循环放在另一个循环中,称为循环嵌套。循环嵌套通常用于遍历多维列表和矩阵。

应用举例

1. 遍历二维列表

```python

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for i in range(len(matrix)):

for j in range(len(matrix[i])):

print(matrix[i][j])

```

输出结果:

```

1

2

3

4

5

6

7

8

9

```

2. 输出九九乘法表

```python

for i in range(1, 10):

for j in range(1, i+1):

print("{}*{}={}".format(j, i, i*j), end="t")

print()

```

输出结果:

```

1*1=1

1*2=2 2*2=4

1*3=3 2*3=6 3*3=9

1*4=4 2*4=8 3*4=12 4*4=16

1*5=5 2*5=10 3*5=15 4*5=20

1*6=6 2*6=12 3*6=18 4*6=24

1*7=7 2*7=14 3*7=21 4*7=28

7*7=49

1*8=8 2*8=16 3*8=24 4*8=32

7*8=56 8*8=64

1*9=9 2*9=18 3*9=27 4*9=36

7*9=63 8*9=72 9*9=81

```

5*5=25

5*6=30

5*7=35

5*8=40

5*9=45

6*6=36

6*7=426*8=486*9=54

总结

Python中for循环的用法可以概括为以下几点:

1. for循环用于遍历序列或其他可迭代的对象。

2. range()函数可以生成一个整数序列。

3. 循环可以嵌套,用于遍历多维列表和矩阵。

4. 循环嵌套可以用于输出九九乘法表等特殊模式。

以上就是Python中for循环的用法的详细介绍。通过学习for循环的用法,可以更好地掌握Python的编程能力,实现更多有用的功能。


本文标签: 循环 序列 遍历 列表