Python 循环嵌套
Python 语言允许在一个循环体里面嵌入另一个循环。
Python for 循环嵌套语法:
for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)
实例:
#!/usr/bin/env python3
a = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
b = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')
for i in range(len(a)):
print(a[i])
for I in range(len(b)):
print(b[I])
print()
Python while 循环嵌套语法:
while expression:
while expression: statement(s) statement(s)
实例:
count = 0
count2 = 0
while (count2 < 3):
while (count < 3):
print('hello:', count)
count = count + 1
print('baby:', count2)
count2 = count2 + 1
运行结果:
hello: 0
hello: 1
hello: 2
baby: 0
baby: 1
baby: 2
你可以在循环体内嵌入其他的循环体,如在while循环中可以嵌入for循环, 反之,你可以在for循环中嵌入while循环。