Python 在特定条件下,如何使用另一个函数打破while循环?
我试图在特定条件下使用while循环中运行的另一个函数来打破它。我一直在写练习代码试图尝试,但它似乎没有打破。。。它一直在无限地运行Python 在特定条件下,如何使用另一个函数打破while循环?,python,Python,我试图在特定条件下使用while循环中运行的另一个函数来打破它。我一直在写练习代码试图尝试,但它似乎没有打破。。。它一直在无限地运行 global test def is_True(): test = True for i in range(5): test = False print("Run number:",i) while(test==False): print("the is_True method hasn't been call
global test
def is_True():
test = True
for i in range(5):
test = False
print("Run number:",i)
while(test==False):
print("the is_True method hasn't been called yet")
is_True()
print("The is__True method was called")
修改is_True()函数:
def is_True():
return True
在循环内部,将其分配给测试:
test = is_True()
您将
global
语句放错了位置。它进入函数以指示test
不是局部变量。全局范围内的global
语句基本上是禁止操作的
def is_True():
global test
test = True
也就是说,尽可能避免全局变量。改为Haveis\u True
returnTrue
,并将返回值分配给调用范围中的test
def is_True():
return True
while not test:
print("...")
test = is_True()
print("...")
这里的问题是
test
变量被定义为函数is_true()中的局部变量,并且没有使用全局变量test
。解决这个问题的最简单方法是告诉python使用全局变量测试。您可以通过更改以下内容来实现:
test = True
到
然而,这并不是最好的解决办法。最好的方法是按照@Vasilis D或@Colin的建议执行,即从is_True()函数返回一个值,并使用该值:
def is_True():
return True
for i in range(5):
test = False
print("Run number:",i)
while(test==False):
print("the is_True method hasn't been called yet")
test = is_True()
print("The is__True method was called")
一般来说,不赞成使用全局变量,因为它会造成混乱的情况,即定义两个同名的不同变量,并且不确定要修改哪一个。很多其他答案都提到了如何解决这个问题,但我想解释一下为什么这样做不起作用也是有帮助的,将来帮忙 在
is_True
中,当您分配给test时,您正在生成一个新的局部变量,而不是引用名为test
的全局变量。如果要引用全局测试,请将global test
添加到is\u True
的开头。这将告诉python您希望引用全局变量,而不是创建新的局部变量
当然,您可能不应该为此使用全局变量,因此更好的解决方案是从
is\u True()
返回True
,然后执行test=is\u True()
以下是我看到的解决方法:
首先,允许方法is_True
具有返回类型、布尔值、真/假,即:
def is_True():
test = True
return test
然后,允许while循环将变量测试重新初始化为返回类型is_True
,即:
print("The is_True method hasn't been called yet")
test = is_True()
这是因为,我怀疑,方法中的变量为True
是私有的,并且仅在该方法中可用。因此,它不会影响全局变量的状态:test
。
总体而言,该计划应类似于:
global test
def is_True():
test = True
return test
for i in range(5):
print("Run number:",i)
test = False
while(test==False):
print("The is_True method hasn't been called yet")
test = is_True()
print("The is_True method was called")
我希望这能回答您的问题,并祝您编码愉快 从is_True返回结果返回
is_True
中的结果,如果结果不是is_True():则将放入循环中。Woops,修复@chepner
global test
def is_True():
test = True
return test
for i in range(5):
print("Run number:",i)
test = False
while(test==False):
print("The is_True method hasn't been called yet")
test = is_True()
print("The is_True method was called")