用功能打破while循环? [英] breaking while loop with function?

查看:217
本文介绍了用功能打破while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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..

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

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

This loops the while loop 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循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆