python - 如果有人输入一个整数,答案中应该有一个字符串,我应该使用哪种错误类型?

标签 python error-handling throw

我知道如何提高错误类型,但我无法弄清楚如果有人在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"

最佳答案

raw_input 始终返回str。因此,如果有人输入123,结果将是'123'(请注意引号)。

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

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

关于python - 如果有人输入一个整数,答案中应该有一个字符串,我应该使用哪种错误类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33272211/

相关文章:

python - BeautifulSoup 抓取新闻文章

vba - 比较两个单元格时获取 “Run-time error ' 1 3': Type mismatch”-错误

apache - 将 PHP 设置为始终在错误 500 时重定向

c# - 异常如何在 C# 中工作(在幕后)

java - 如何抛出不会终止我的程序的 IllegalArgumentException?

python - Hdf5 和 pickle 比原始 csv 文件占用更多空间

python - 使用两个不同版本的python,但sqlmap需要2.7

python - AWS EC2 Django runserver 端口 8000 出现问题

javascript - 在服务器端捕获所有 JavaScript 客户端错误

java - Controller 级别的两个 try catch block