首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么while循环不能在另一个循环中工作(for in range)

为什么while循环不能在另一个循环中工作(for in range)
EN

Stack Overflow用户
提问于 2019-08-30 16:04:26
回答 1查看 336关注 0票数 0

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

while不会在需要时中断循环。我怎么才能修复它?

代码语言:javascript
复制
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时停止

EN

回答 1

Stack Overflow用户

发布于 2019-08-30 16:09:13

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

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57722866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档