“绞刑游戏, 循环中断和sys.exi”

2024-10-05 12:20:01 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我想知道是否有任何方法可以让一个循环被中断,我已经尝试使用break命令,但这没有任何作用。我是新来的。在

另外,当人们使用命令时,有没有办法让它优雅地关闭:

wannaplay = raw_input('Wanna play hangman?(yes or no): ')"

我试过了系统出口这也是例外。在

这是我的代码:

^{pr2}$

Tags: or方法no代码命令inputplayraw
1条回答
网友
1楼 · 发布于 2024-10-05 12:20:01

使用异常来中断循环。考虑下面的例子

try:
    while True:
        answer = raw_input("Type [Y]es to Exit :")
        if answer.lower() in ["yes","y"]: raise StopIteration
        print "Your answer is ", answer
except StopIteration:
    print "Good Bye"


Type [Y]es to Exit :No
Your answer is  No
Type [Y]es to Exit :Why
Your answer is  Why
Type [Y]es to Exit :I Won't
Your answer is  I Won't
Type [Y]es to Exit :Ok
Your answer is  Ok
Type [Y]es to Exit :Yes
Good Bye

实际上,您可以在多个级别组合多个出口。考虑下一个例子

^{pr2}$

相关问题 更多 >

    热门问题