如果用户输入无效,我想要发生一些事情(查看异常块):
try:
name = raw_input("\nEnter someone's name (x to exit): ")
table_dictionary[name.title()] # This is what I am talking about
fact = raw_input("What do you want to know about " + name.title() + "?: ")
print name.title() + "'s " + fact + " is " + str(table_dictionary[name.title()][fact.title()])
except KeyError:
if name == "x":
print 'Closing'
break
print "Error: Invalid input"
注意我是如何运行table_dictionary[name.title()]
的,即使它没有做任何事情。如果用户输入不在字典中,我会这样做,它会告诉用户它是无效输入。 PyCharm突出显示它并告诉我statement seems to have no effect
。我只是想知道这是不是很好的做法。
编辑:请注意,如果用户也提供无效输入,我还要打印“错误:输入无效”。我的例子涵盖了这一点。
答案 0 :(得分:3)
我认为这更优雅和更加抒情:
name = raw_input("\nEnter someone's name (x to exit): ")
if name == "x":
print 'Closing'
break
try:
fact_dictionary = table_dictionary[name.title()]
fact = raw_input("What do you want to know about " + name.title() + "?: ")
print name.title() + "'s " + fact + " is " + str(fact_dictionary[fact.title()])
except KeyError:
print "Error: Invalid input"
这样我们就可以捕获无效输入的两个可能异常,并在name == 'x'
它还使您的代码更具可读性并阻止PyCharm抱怨。
我不同意其他一些建议检查词典中的键等的评论者,你是正确的使用流控制的例外,EAFP是Python方式。
答案 1 :(得分:1)
检查table_dictionary中的键可能是更好的做法
name = raw_input("\nEnter someone's name (x to exit): ")
if name == "x":
print 'Closing'
break
elif name.title() not in table_dictionary:
print "Error: Invalid input"
else:
fact = raw_input("What do you want to know about " + name.title() + "?: ")
print name.title() + "'s " + fact + " is " + str(table_dictionary[name.title()][fact.title()])
为了更好的可读性,您可以将.title()直接移动到输入
name = raw_input("\nEnter someone's name (x to exit): ").title()
if name == "X":
print 'Closing'
break
elif name not in table_dictionary:
print "Error: Invalid input"
else:
fact = raw_input("What do you want to know about " + name + "?: ")
print name + "'s " + fact + " is " + str(table_dictionary[name][fact.title()])
答案 2 :(得分:0)
运行一些代码只是为了查看它是否会引发异常,但通常会有更好的方法来测试是否有可能。在您的具体情况下,我建议使用in
运算符测试密钥是否在字典中,使用if
,elif
和else
来解决后果:
name = raw_input("\nEnter someone's name (x to exit): ")
if name.title() in table_dictionary:
fact = raw_input("What do you want to know about " + name.title() + "?: ")
print name.title() + "'s " + fact + " is " + str(table_dictionary[name.title()][fact.title()])
elif name == "x":
print 'Closing'
break
else:
print "Error: Invalid input"
答案 3 :(得分:0)
我建议做这样的事情。现在没有什么是无用的。
strcmp()
答案 4 :(得分:0)
您可以
_ = table_dictionary[name.title()] # This is what I am talking about
因为使用Python约定使用下划线_表示未使用此变量。否则pycharm会抱怨未使用的变量。