首页 > 解决方案 > 为什么while循环在另一个循环中不起作用(for in range)

问题描述

我想使用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时停止

标签: pythonpython-3.xloopswhile-looppython-3.7

解决方案


试试这个——为了从子程序内部与全局变量交互——你需要指出它是全局的。否则它只是与现有全局变量同名的局部函数变量

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)

推荐阅读