python的嵌套循环有哪些经典例题
时间: 2023-09-03 18:09:52 浏览: 132
Python的嵌套循环可以用于解决很多问题,以下是一些经典例题:
1. 打印九九乘法表
```python
for i in range(1, 10):
for j in range(1, i+1):
print("{}*{}={}".format(j, i, i*j), end="\t")
print()
```
2. 输出100以内的素数
```python
for i in range(2, 101):
flag = True
for j in range(2, i):
if i % j == 0:
flag = False
break
if flag:
print(i)
```
3. 输出斐波那契数列
```python
a, b = 0, 1
while a < 1000:
print(a, end=',')
a, b = b, a+b
```
4. 输出杨辉三角
```python
def yanghui_triangle(n):
triangle = [[1] * (i+1) for i in range(n)]
for i in range(2, n):
for j in range(1, i):
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]
return triangle
n = 10
triangle = yanghui_triangle(n)
for i in range(n):
print(' '*(n-i), end=' ')
for j in range(i+1):
print(triangle[i][j], end=' ')
print()
```
这些例子展示了嵌套循环的用法,但实际上嵌套循环还可以用于更复杂的问题,如图像处理、模拟等领域。
阅读全文