简体   繁体   English

for循环在while循环python中

[英]For loop inside while loop python

I have a function that needs to be called inside a loop is a condition is true. 我有一个需要在循环内调用的函数,如果条件为真。 I have to call the function an x amount of times. 我必须多次调用该函数。 I tried putting the for loop inside the while loop, but then the function kept getting called over and over again. 我尝试将for循环放入while循环中,但随后该函数不断被调用。 I made an example: 我举了一个例子:

gamescene = 0
x = 0

def function():
    global x
    x = x + 1
    print(x)

while True:
    if gamescene == 0:
        for y in range(5):
            function()

I want the function to only print out x times, but because it's in a loop, it prints forever and I don't know how to get around it. 我希望该函数仅打印出x次,但是由于它处于循环状态,因此它将永远打印,并且我不知道如何解决它。

Maybe you have to check the value of x : 也许您必须检查x的值:

def function():
    global x
    x = x + 1
    if x <= 5: print(x)

The problem lies within 问题出在

while True

This continuously repeats the code under it, so it checks after 5 times if the gamescene is 0 again, repeat is another 5 times etc. 这会不断重复其下的代码,因此它会在5次之后检查游戏场景是否再次为0,是否再次重复5次,等等。

You should change the gamescene to be nonzero within the while loop, or remove the while loop. 您应在while循环内将游戏场景更改为非零,或删除while循环。

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

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