Rya*_*ord 7 python function break
我正在尝试创建一个包含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')
Run Code Online (Sandbox Code Playgroud)
现在我不确定我是否正在使用该功能,但是当我尝试它时,它说我不能在功能上中断.因此,如果有人可以帮助我解决这个问题,如果你能帮助我,如果函数和调用函数本身的格式错误,那将非常感激.
glg*_*lgl 10
您可以使用例外:
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
Run Code Online (Sandbox Code Playgroud)
这会循环while遍历循环,但在yn()函数内部会引发异常,从而打破循环.为了不打印回溯,必须捕获并处理异常.
您需要在循环本身中跳出 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
Run Code Online (Sandbox Code Playgroud)