擅长:python、mysql、java
<p>你可以例外地工作:</p>
<pre><code>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
</code></pre>
<p>这会反复循环<code>while</code>循环,但在<code>yn()</code>函数内部会引发异常,从而中断循环。为了不打印回溯,必须捕获并处理异常。</p>