简体   繁体   English

打破while循环的功能?

[英]breaking while loop with function?

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. 我正在尝试制作一个具有if / elif语句的函数,并且我希望if中断while循环。该函数用于文本冒险游戏,是/否的问题。 Here is what i have come up with so far.. 到目前为止,这是我想出的。

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. 因此,如果有人可以帮助我解决该问题,并且如果函数和调用函数本身的格式错误,则可以帮助我,将不胜感激。

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 while loop over and over, but inside the yn() function an exception is raised which breaks the loop. 这样一遍又一遍地循环while循环,但是在yn()函数内部,引发了一个异常,该异常打破了循环。 In order to not print a traceback, the exception must be caught and processed. 为了不打印回溯,必须捕获并处理异常。

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

You will need to change the break inside your function to a return, and you need to have an else statement in case that the user did not provide you with the correct input. 您需要将函数内部的中断更改为return,并且需要使用else语句,以防用户未向您提供正确的输入。 Finally you need to turn the call in your while loop into a if statement. 最后,您需要将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. 如果玩家输入了所需的命令,这将使您打破while语句,否则,它将再次询问。 I also updated your yn function to allow the user to use both lower and upper case characters, as well as yes and no. 我还更新了yn函数,以允许用户同时使用大小写字符以及yes和no。

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 yn function has three states. yn函数具有三种状态。 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. 如果用户响应为“是”或“否”,则该函数将返回1(是)和2(否)。 And if the user does not provide valid input, eg a blank-space , it will return 0. 并且,如果用户没有提供有效的输入,例如空格,它将返回0。

Inside the while True: loop we wrap the yn('....', '....') function with an if statement that checks if the yn function returns a number larger than 0. Because yn will return 0 if the user provides us with an valid input, and 1 or 2 for valid input. while True:循环中,我们使用if statement包装yn('....','....')函数,该if statement检查yn函数是否返回大于0的数字。因为yn将返回0。用户为我们提供了有效输入,有效输入为1或2。

Once we have a valid response from yn we call break, that stops the while loop and we are done. 一旦收到来自yn的有效响应,我们将调用break,这将终止while loop ,并完成了操作。

One approach would be to have yn return a boolean value which then would be used to break out of the loop. 一种方法是让yn返回一个布尔值,然后将其用于中断循环。 Otherwise a break within a function cannot break out of a loop in the calling function. 否则,函数内的break无法脱离调用函数中的循环。

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')

Using break , you can come out of the loop even if the condition for the end of the loop is not fulfilled. 使用break,即使不满足循环结束的条件,也可以退出循环。 You cant have break because 'if /elif ' is not a loop, its just a conditional statement. 您无法中断,因为'if / elif'不是循环,它只是一个条件语句。

a = True

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM