用函数打破 while 循环?

新手上路,请多包涵

我正在尝试制作一个包含 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')

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

原文由 Ryan Hosford 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 433
2 个回答

您可以处理例外情况:

 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

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

编辑(九年多后):

在我看来,我忘记了“y”的情况。那么,让我们以不同的方式进行:

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

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

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

# decided is not None now, so can only be False or True.
if decided:
    play()
else:
    pass
    # or print "Goodbye." if you want

原文由 glglgl 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

 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

原文由 Duane Moore 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题