Python 用函数打破while循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16073396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:43:06  来源:igfitidea点击:

breaking while loop with function?

pythonfunctionbreak

提问by Ryan Hosford

I am trying to make a function that has an if/elif statement in it, and I want the if to break a while loop.. The function is for a text adventure game, and is a yes/no question. Here is what i have come up with so far..

我正在尝试创建一个包含 if/elif 语句的函数,并且我希望 if 中断 while 循环。该函数用于文本冒险游戏,是一个是/否问题。这是我到目前为止想出的..

def yn(x, f, g):
    if (x) == 'y':
         print (f)
         break
    elif (x) == 'n'
         print (g)

name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'

while True:
    ready = raw_input('y/n ')
    yn(ready, 'Good, let\'s start our adventure!', 
       'That is a real shame.. Maybe next time')

Now I'm not sure if I am using the function right, but when I try it out, it says I can't have break in the function. So if someone could help me with that problem, and if you could help me if the function and calling the function itself is formatted wrong, that would be very much appreciated.

现在我不确定我是否正确使用了该函数,但是当我尝试它时,它说我不能在该函数中中断。因此,如果有人可以帮助我解决这个问题,并且如果函数和调用函数本身的格式错误,如果您可以帮助我,那将不胜感激。

采纳答案by glglgl

You can work with an exception:

您可以处理异常:

class AdventureDone(Exception): pass

def yn(x, f, g):
    if x == 'y':
         print(f)
    elif x == 'n':
         print(g)
         raise AdventureDone

name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'

try:
    while True:
        ready = raw_input('y/n ')
        yn(ready, "Good, let's start our adventure!",
           'That is a real shame.. Maybe next time')
except AdventureDone:
    pass
    # or print "Goodbye." if you want

This loops the whileloop over and over, but inside the yn()function an exception is raised which breaks the loop. In order to not print a traceback, the exception must be caught and processed.

while一遍又一遍地循环循环,但在yn()函数内部引发了一个异常,从而中断了循环。为了不打印回溯,必须捕获并处理异常。

回答by Ed Plese

One approach would be to have ynreturn a boolean value which then would be used to break out of the loop. Otherwise a breakwithin a function cannot break out of a loop in the calling function.

一种方法是yn返回一个布尔值,然后将其用于跳出循环。否则break,函数内的 a 不能跳出调用函数中的循环。

def yn(x, f, g):
    if (x) == 'y':
        print (f)
        return True
    elif (x) == 'n'
        print (g)
        return False

name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'
done = False
while not done:
    ready = raw_input('y/n ')
    done = yn(ready, 'Good, let\'s start our adventure!', 'That is a real shame.. Maybe next time')

回答by dharag

Using break , you can come out of the loop even if the condition for the end of the loop is not fulfilled. You cant have break because 'if /elif ' is not a loop, its just a conditional statement.

使用 break ,即使没有满足循环结束的条件,您也可以退出循环。你不能有 break 因为 'if /elif ' 不是一个循环,它只是一个条件语句。

回答by Duane Moore

You need to break out of the while loop within the loop itself, not from within another function.

您需要在循环本身内跳出 while 循环,而不是从另一个函数内跳出。

Something like the following could be closer to what you want:

像下面这样的东西可能更接近你想要的:

def yn(x, f, g):
    if (x) == 'y':
        print (f)
        return False
    elif (x) == 'n':
        print (g)
        return True

name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'

while True:
    ready = raw_input('y/n: ')
    if (yn(ready, 'Good, let\'s start our adventure!', 'That is a real shame.. Maybe next time')):
        break

回答by eandersson

You will need to change the break inside your function to a return, and you need to have an elsestatement in case that the user did not provide you with the correct input. Finally you need to turn the call in your while loopinto a if statement.

您需要将函数内的中断更改为返回,并且您需要有一个else声明,以防用户没有为您提供正确的输入。最后,您需要将您的调用while loop转换为 if 语句。

This will allow you to break the while statement if the player enters the desired command, if not it will ask again. I also updated your ynfunction to allow the user to use both lower and upper case characters, as well as yes and no.

如果玩家输入所需的命令,这将允许您中断 while 语句,否则它将再次询问。我还更新了您的yn函数,以允许用户同时使用小写和大写字符,以及是和否。

def yn(input, yes, no):
    input = input.lower()
    if input == 'y' or input == 'yes':
        print (yes)
        return 1
    elif input == 'n' or input == 'no':
        print (no)
        return 2
    else:
        return 0

name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, %s. Are you ready for your adventure?' % name

while True:
    ready = raw_input('y/n ')
    if yn(ready, 'Good, let\'s start our adventure!',
       'That is a real shame.. Maybe next time') > 0:
        break

The idea behind this is pretty simple. The ynfunction has three states. Either the user responded with yes, no or invalid. If the user response is either yes or no, the function will return 1 for yes, and 2 for no. And if the user does not provide valid input, e.g. a blank-space , it will return 0.

这背后的想法非常简单。该yn函数具有三种状态。用户回答是、否或无效。如果用户响应为是或否,则该函数将返回 1 表示是,2 表示否。如果用户没有提供有效的输入,例如一个空格,它将返回 0。

Inside the while True:loop we wrap the yn('....', '....') function with an if statementthat checks if the ynfunction returns a number larger than 0. Because ynwill return 0 if the user provides us with an valid input, and 1 or 2 for valid input.

while True:循环中,我们将 yn('....', '....') 函数用 an 包装起来,以if statement检查该yn函数是否返回大于 0 的数字。因为yn如果用户向我们提供了有效输入,则返回 0 , 1 或 2 表示有效输入。

Once we have a valid response from ynwe call break, that stops the while loopand we are done.

一旦我们从yn我们调用 break 中获得有效响应,就会停止while loop,我们就完成了。

回答by John H

a = True

def b():
    if input("") == "Quit":
        global a
        a == False
    else:
        pass

while a == True:
    print('Solution')