Python循环重新启动,即使有一个尝试:除了:

时间:2013-01-18 22:51:12

标签: python loops except

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

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循环。如果您输入的数字不是数字,它将告诉您只允许使用数字。

然而,在第二个循环中,它要求您输入yes或no,但如果输入不同的内容,它只会重新启动循环而不是在

之后打印消息
except:

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

1 个答案:

答案 0 :(得分:4)

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

相反,在elseyes测试中添加no语句:

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()需要任何 python表达式。如果我输入"Hello program"(带引号),则不会引发任何异常,但它也不是数字。请改为使用int(raw_input()),然后捕获ValueError(如果您输入的不是整数,则会抛出什么)和EOFError 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