Python 使用函数中断while True循环
所以我有一个真正的循环-Python 使用函数中断while True循环,python,python-2.7,while-loop,Python,Python 2.7,While Loop,所以我有一个真正的循环- while True: getStatus() print('Ended') 如果答案是999,我希望能够突破它。这就是我所尝试的: def getStatus(): answer = input('What is the box ID? ') if answer == 999: return False elif type(answer) == int: boxId = answer + 1 print(boxId)
while True:
getStatus()
print('Ended')
如果答案是999,我希望能够突破它。这就是我所尝试的:
def getStatus():
answer = input('What is the box ID? ')
if answer == 999:
return False
elif type(answer) == int:
boxId = answer + 1
print(boxId)
然而,即使输入为“999”,它也会返回并询问“盒子ID是什么?”再说一遍
如何摆脱while-true循环?您的
while
循环一直在循环,因为这正是您告诉它要做的。在从函数体调用的函数返回后,忽略返回值,无条件地打印“end”
,然后再次执行所有操作,因为循环中的条件显然仍然真实
如果希望函数控制循环是否继续,则应使用其返回值作为循环中的条件,如下所示:
running = True
while running:
running = getStatus()
print("Ended") # move this outside the loop!
这要求getStatus
在希望保持循环时返回一个truthy值,在希望停止循环时返回一个false值。您当前对该函数的实现不能做到这一点。当输入999
时,它返回False
,但如果您提供其他输入,它不会显式返回任何内容(在Python中,这相当于返回None
)。由于False
和None
都是错误的,因此上面的代码实际上无法工作(您可以使用类似running=getStatus()is None
的内容对其进行修补,但这将非常可怕)。您应该将函数更改为在其所有分支中都有一个显式的return
语句(包括非整数输入的情况,其中它不进入if
或elif
块)
如果循环和函数的逻辑紧密地交织在一起,那么将循环移动到函数本身可能是有意义的,而不是将其分开并需要使用返回值来指示何时停止。在单个函数中,您可以使用break
直接退出循环:
def getStatus():
while True:
answer = input('What is the box ID? ')
if answer == 999:
break
elif isinstance(answer, int): # isinsance() is better than type(...) == ...
boxId = answer + 1
print(boxId)
else:
print("I'm sorry, I didn't understand that.") # still good to handle this case
你可以把它改成-
如果(不是getstatus()):
中断
这样,您就可以使用返回值来打破无限循环。
很简单
def selectedCountry():
while True:
country = input("Enter country of which you want to check pictures HR, RS, RO: ").upper()
if country == str("HR") or country == str("RO") or country == str("RS"):
break
else:
print("Please enter HR or RO or RS: " + "you wrote: " + country)
为什么True在函数外部工作,而在函数内部工作时又会再次询问相同的问题
Enter country of which you want to check pictures HR, RS, RO: >? hr
Enter country of which you want to check pictures HR, RS, RO:
您可以在get_status()之前添加if语句,该语句将检查它是否为true和break,并且在get_status函数中,必须返回true才能break
def getStatus():
answer = input('What is the box ID? ')
if answer == 999:
return True
elif type(answer) == int:
boxId = answer + 1
print(boxId)
while True:
if getStatus():
print('Ended')
break
@cᴏʟᴅsᴘᴇᴇᴅ: 我不认为使用
输入是这个问题的真正问题。在Python2中,input
将返回一个数字,getStatus
函数应该或多或少可以工作(它将返回False
或None
,这不是区分成功与失败的好方法)。虽然在Python2中,print
不是函数,但谁知道真正使用的是哪个版本呢。不管怎样,我要重新打开。@Blckknght仔细检查一下。。。是的,我认为这是getStatus
'返回值在while
循环中未被测试的问题。欢迎使用堆栈溢出!您可以通过将代码缩进四个额外的空格来格式化代码(除了您希望代码内部具有的缩进之外)。一个简单的方法是在编辑器中选择它,然后单击{}
按钮。如果您选择了多行,它将为您缩进所有行。如果您只有一行(或者只有一行的一部分),它将使用backticks``来代替(这对于在文本中放入变量名之类的代码片段非常有用)!我可以知道我的代码的哪一部分应该改为你的吗?Hello@user2498462,为了让你的答案更容易理解,你应该使用与问题中使用的相同的代码。这段代码不仅在逻辑结构上有很大的问题,而且在完全忽略主要问题的情况下也非常容易出错