# 一、说明

Python 嵌套 While 循环的语法；嵌套while循环的基本语法如下：

```#outer  while loop
while condition:

#inner while loop
while condition:
block of code
block of code```

1. Outer While Loop
2. Inner While Loop

## 二、嵌套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```

1. Since 2<=5, the outer loop gets executed

1. Initially j=1 and since 1<=2 inners for loop is executed
2. Print j as 1 and increment j
3. Again check the condition, 2<=2, and the inner loop is executed
4. Print j as 2 and increment j
5. Now since 3<=2 is False so we get out of the inner loop

## 三、实时嵌套循环例

``````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):
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 循环，直到计数器变量变为零。

原文作者：无水先生
原文地址: https://blog.csdn.net/gongdiwudu/article/details/125319593
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。