简体   繁体   English

为什么 Python for 循环没有在内部循环使用 while 循环

[英]Why is Python for loop not looping with a while loop inside

I am really curious about this.我真的很好奇这个。

I have a for loop that is looping through a list.我有一个循环遍历列表的 for 循环。 Inside the for loop I have a while loop that I want to loop through till a condition is met.在 for 循环中,我有一个 while 循环,我想循环它直到满足条件。 When the condition of the while loop is met, stop the while loop and move to the next item of the list and start the while loop again.当满足while循环的条件时,停止while循环并移动到列表的下一项并再次启动while循环。

Here is the example code:这是示例代码:

course_ids = [1,2,3,4,5]

loop_control = 0
counter = 0

for ids in course_ids:
    while loop_control == 0:
        counter = counter + 1
        if counter == 2:
            loop_control = 1

The problem is that when the while loop condition is met, it breaks out of the for loop altogether.问题在于,当满足 while 循环条件时,它会完全脱离 for 循环。

How do I get the for loop to work as intended with a while loop inside of it?如何让 for 循环按预期工作,其中有一个 while 循环?

You set loop control to 1 in the if statement.您在 if 语句中将循环控制设置为 1。 The while loop is set to only run if loop control is equal to 1. So basically the first time it runs, you set the condition to never run again. while 循环设置为仅在循环控制等于 1 时运行。所以基本上第一次运行时,您将条件设置为不再运行。

If you were to reset loop control to zero on each iteration of the for loop, the while will run each time.如果您在 for 循环的每次迭代中将循环控制重置为零,则每次都会运行 while。

course_ids = [1,2,3,4,5]

# loop_control = 0 <-- Remove this line
counter = 0

for ids in course_ids:
    loop_control = 0 # place this line and see it work more than once.
    while loop_control == 0:
        counter = counter + 1
        if counter == 2:
            loop_control = 1

Your assumption is wrong that it breaks out of the for loop altogether.你的假设是错误的,它完全脱离了 for 循环。 It doesn't, it runs but the while condition is never True and hence it never runs inside it.它不会,它会运行,但 while 条件永远不会为True ,因此它永远不会在其中运行。

You can also check this by adding a print statement inside the for loop and see its output.您还可以通过在 for 循环中添加打印语句并查看其输出来检查这一点。

course_ids = [1,2,3,4,5]

loop_control = 0
counter = 0

for ids in course_ids:
    print("here")
    while loop_control == 0:
        counter = counter + 1
        if counter == 2:
            loop_control = 1

Output:输出:

here
here
here
here
here

As you can see it ran 5 times as expected.如您所见,它按预期运行了 5 次。 You should also consider visualizing the code to get a better understanding, see here您还应该考虑将代码可视化以获得更好的理解,请参见此处

you all are right.你们都是对的。

I did not reset the while loop condition我没有重置 while 循环条件

I have added these lines after the for loop and it fixed the issue我在 for 循环之后添加了这些行并解决了问题

if counter != len(course_ids):
    loop_control = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM