为什么while循环在另一个循环内不起作用(在范围内)

时间:2019-08-30 08:04:26

标签: python python-3.x loops while-loop python-3.7

我想使用while(数字从0到1000000)运行一个函数(def)100次

但是while并不会在需要时中断循环。 我该如何解决?

count = 2  #I start from 2 on purpose
limit = 101

def is_prime(i):
    global count
    count+=1
    #there is more to the function is_prime but it isn't relevant 
    #i made a function with input to show a example

while (count < limit):
    for i in range(1000000):
        is_prime(i)
        print ("count = ", count)

我希望它在count = 100时停止运行

1 个答案:

答案 0 :(得分:0)

尝试执行此操作-为了与子例程内部的全局变量进行交互-您需要指示其为全局变量。否则,它就是与现有全局变量同名的局部函数变量

count = 2  #I start from 2 on purpose
limit = 101

def is_prime(i):
    global count
    count+=1
    #there is more to the function is_prime but it isn't relevant 
    #i made a function with input to show a example

while (count < limit):
    for i in range(1000000):
        is_prime(i)
        print ("count = ", count)
print(count)