python - 为什么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时停止
解决方案
试试这个——为了从子程序内部与全局变量交互——你需要指出它是全局的。否则它只是与现有全局变量同名的局部函数变量
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)
推荐阅读
- r - 无法导出绘图:R 代码执行错误/无法启动 png() 设备
- javascript - 录制语音消息 - javascript
- javascript - 如何使用 JavaScript 将伪元素直接设置为 html
- mysql - 如何查找捐助者姓名及其一年的捐款总额,包括 ID 为 NULL 的匿名捐助者
- python-3.x - 如何在 MacOS 上安装 PyQt5?
- mysql - 无法添加或更新子行:即使我已经在父表上添加了行,外键约束也会失败
- java - 应用程序上下文获取空值
- google-sheets - 如何在谷歌表格中的公式中返回一个值
- c# - C#浮点到字符串分隔符
- r - stargazer 中多个多项式模型的变量名称