当前位置: 代码迷 >> python >> 如果有人输入一个整数而答案中应该有一个字符串,我应该使用什么错误类型?
  详细解决方案

如果有人输入一个整数而答案中应该有一个字符串,我应该使用什么错误类型?

热度:117   发布时间:2023-06-13 15:16:34.0

我知道如何提高错误类型,但如果有人在raw_input的字符串中输入一个整数,我无法弄清楚我应该使用哪个错误。

这是我的代码:

try:
    print "Welcome to my Quiz!"
    points = 0

    #Asks the user the first question and check to see if the answer is right and gives them a point if they are
    question1 = raw_input("Here's question #1! What is the name of Spongebob's pet?")

    if (question1.lower()) == "gary":
        print "You are correct!"
        points +=1
    else:
        print "You are wrong!"

    #Asks the user the second question and check to see if the answer is right and gives them a point if they are
    question2 = raw_input("Here's question #2! Whos is Spongebob's best friend?")

    if (question2.lower()) == "patrick":
        print "You are correct!"
        points +=1
    else:
        print "You are wrong!"

    #Asks the user the third question and check to see if the answer is right and gives them a point if they are
    question3 = raw_input("Here's question #3! Where does Spongebob work?")

    if (question3.lower()) == "krusty krab" or (question3.lower()) == "the krusty krab":
        print "You are correct!"
        points +=1
    else:
        print "You are wrong!"

    print "Thanks for playing my quiz! You got", points, "answers right out of 5! Nice job!"

except ValueError, errorvar:
    print errorvar

except NameError:
    print "Please enter a number for the correct variables, thanks"

except:
    print "An error has occurred"

总是返回一个str 所以如果有人输入123 ,结果将是'123' (注意引号)。

在其他情况下,您以某种方式有一个返回int的函数,其中代码需要一个str (例如您如何在raw_input的结果上立即调用lower ), int不会有一个lower方法,因此尝试调用应该会导致AttributeError .

>>> (0).lower()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'lower'
  相关解决方案