2

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

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:

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

4

1 回答 1

4

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

相反,在您的or测试中添加一条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陈述;捕获特定的异常。否则,您将掩盖不相关的问题,使您更难发现这些问题。

您的第一个 except 处理程序应该只 catch ,NameError例如:EOFErrorSyntaxError

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()),然后 catch ValueError(如果你输入任何不是整数的东西会抛出什么)和EOFErrorfor raw_input

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

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

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
于 2013-01-18T22:53:28.940 回答