一、说明
循环在 python 中很重要,因为没有它们,我们将不得不一遍又一遍地重复指令,这对程序员来说可能很耗时。 while 循环仅评估给定条件,如果为真,则执行一组语句,直到该条件为真。但是如果问题的复杂性增加了,那么就有必要在另一个while循环中插入一个while循环。因此,在本教程中,您将了解 Python 中的嵌套 while 循环。
Python 嵌套 While 循环的语法;嵌套while循环的基本语法如下:
#outer while loop while condition: #inner while loop while condition: block of code block of code
嵌套的 while 循环包含两个基本组件:
- Outer While Loop
- Inner While Loop
外部 while 循环可以包含多个内部 while 循环。这里的条件产生一个布尔值,如果它为真,那么只有循环才会被执行。对于外循环的每次迭代,内循环都从头开始执行,这个过程一直持续到外循环的条件为真。类似地,只有当它的条件为真并且代码块被执行时,内部的 while 循环才会被执行。
二、嵌套while循环流程图
首先,评估外循环条件。如果为假,则控制跳转到外部 while 循环的末尾。如果条件为真,则控制跳转到内部 while 循环条件。接下来,评估内部 while 循环条件。如果为假,则控制跳回外部 while 循环条件。如果为真,则执行内部 while 循环内的代码块。
嵌套 while 循环的简单示例
在此示例中,我们使用嵌套的 while 循环创建数字模式
i=1
while i<=5:
j=1
while j<=i:
print(j,end=" ")
j=j+1
print("")
i=i+1
Output:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
在上面的代码中,外部 while 循环跟踪模式内的每个新行,内部 while 循环根据条件显示数字。
示例, if i=2
外循环:-
- Since 2<=5, the outer loop gets executed
内循环:-
- Initially j=1 and since 1<=2 inners for loop is executed
- Print j as 1 and increment j
- Again check the condition, 2<=2, and the inner loop is executed
- Print j as 2 and increment j
- Now since 3<=2 is False so we get out of the inner loop
三、实时嵌套循环例
问题陈述
考虑一个在线问答游戏,用户必须写出给定单词的同义词,并且只有 3 次正确尝试问题的机会。
synonyms=['pretty','alluring','lovely']
counter=3
while counter>0:
answer=input("What is the synonym of 'Beautiful': ")
status=True
i=0
while i<len(synonyms):
if(synonyms[i]==answer):
print("Correct!!")
counter=-1
break
else:
status=False
i=i+1
if(status==False):
print("Incorrect!!")
counter=counter-1
print(f"You have {counter} chances")
Output:
What is the synonym of 'Beautiful': ugly Incorrect!! You have 2 chances What is the synonym of 'Beautiful': bad Incorrect!! You have 1 chances What is the synonym of 'Beautiful': pretty Correct!!
在上面的代码中,我们使用了一个计数器变量来存储尝试的次数,并且外部的 while 循环验证只给了用户 3 次尝试。我们还有一个名为同义词的列表,用于存储问题的有效答案。内部的 while 循环遍历列表并检查用户是否提供了正确的答案。如果提供的答案是正确的,那么它只是从内部循环中中断并退出程序,因为计数器变量等于 -1。如果答案不正确,则计数器变量递减并再次执行内部 while 循环,直到计数器变量变为零。