【问题标题】:Python loop restarting even though there is a try: except:即使有尝试,Python循环也会重新启动:除了:
【发布时间】:2013-01-02 18:05:20
【问题描述】:

这是我刚刚编写的一个小程序的代码,用于测试我学到的一些新东西。

while 1:
    try:
        a = input("How old are you? ")
    except:
        print "Your answer must be a number!"
        continue

    years_100 = 100 - a
    years_100 = str(years_100)
    a = str(a)
    print "You said you were "+a+", so that means you still have "+years_100+" years"
    print "to go until you are 100!"
    break
while 2:
    try:
        b = str(raw_input('Do you want to do it again? If yes enter "yes", otherwise type "no" to stop the script.'))
    except:
        print 'Please try again. Enter "yes" to do it again, or "no" to stop.'
        continue

    if b == "yes":
            print 'You entered "yes". Script will now restart... '
    elif b == "no":
            print 'You entered "no". Script will now stop.' 
            break

它适用于 for 循环。如果您输入的不是数字,它会告诉您只允许输入数字。

但是,在第二个循环中,它会要求您输入是或否,但如果您输入不同的内容,它只会重新启动循环而不是在之后打印消息

except:

我做错了什么以及如何解决它以显示我告诉它的消息?

【问题讨论】:

  • 请不要盲目地捕捉任何异常——这是非常糟糕的做法,因为它很难发现错误——相反,捕捉你正在管理的确切异常。还值得注意的是,while 1: 最好使用 while True - 您还应该将不希望重复的内容移出循环。

标签: python loops except


【解决方案1】:

您不会遇到异常,因为您在使用raw_input()总是输入字符串。因此str() 的返回值raw_input() 永远不会失败。

相反,将else 语句添加到您的yesno 测试中:

if b == "yes":
        print 'You entered "yes". Script will now restart... '
elif b == "no":
        print 'You entered "no". Script will now stop.' 
        break
else:
    print 'Please try again. Enter "yes" to do it again, or "no" to stop.'
    continue

请注意,您永远不应该使用笼统的except 声明;捕获特定异常。否则,你会掩盖不相关的问题,让你更难发现这些问题。

您的第一个异常处理程序应该只捕获 NameErrorEOFErrorSyntaxError,例如:

try:
    a = input("How old are you? ")
except (NameError, SyntaxError, EOFError):
    print "Your answer must be a number!"
    continue

因为这就是 input() 会抛出的。

还要注意input() 采用any python 表达式。如果我输入"Hello program"(带引号),不会引发异常,但它也不是数字。改用int(raw_input()),然后捕获ValueError(如果您输入任何不是整数的东西会抛出什么)和EOFError for raw_input

try:
    a = int(raw_input("How old are you? "))
except (ValueError, EOFError):
    print "Your answer must be a number!"
    continue

要使用第二个循环来控制第一个循环,请将其设为返回 TrueFalse 的函数:

def yes_or_no():
    while True:
        try:
            cont = raw_input('Do you want to do it again? If yes enter "yes", otherwise type "no" to stop the script.'))
        except EOFError:
            cont = ''  # not yes and not no, so it'll loop again.
        cont = cont.strip().lower()  # remove whitespace and make it lowercase
        if cont == 'yes':
            print 'You entered "yes". Script will now restart... '
            return True
        if cont == 'no':
            print 'You entered "no". Script will now stop.' 
            return False
        print 'Please try again. Enter "yes" to do it again, or "no" to stop.'

在另一个循环中:

while True:
    # ask for a number, etc.

    if not yes_or_no():
        break  # False was returned from yes_or_no
    # True was returned, we continue the loop

【讨论】:

  • 好的,非常感谢您的帮助!另外,有没有办法返回到第一个循环?
  • 你必须嵌套循环,或者使用一个函数(当输入yes时返回True,或者False代表no,然后使用该返回值来中断或继续。
  • 如果while 1:中有循环,你能用它来返回1吗?
  • 在第一个 while 循环的末尾使用它而不是 break。创建一个向用户询问yesno 的函数(在你现在拥有的循环中),并使用返回值。
  • raw_input() 可能会引发 EOFError
猜你喜欢
  • 2010-10-04
  • 2022-01-13
  • 2021-12-19
  • 2020-02-10
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多