gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:10:13 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com