除了一些代码,我正在尝试使用try和。我可以让代码的try部分正常工作,但不能让例外部分正常工作。我正在使用ValueError,但已经尝试过NameError和IndexError。我遗漏了什么?
string1 = input("Enter a string:")
d = dict(enumerate(string1))
try:
enter_value = input("Enter a value(should be in the initial string1):")
if enter_value in d.values():
print("Value found.")
except ValueError:
print("Value not found.")当enter_value在dict()中时,我编写的代码会产生正确的响应。但显示:“输入一个值(应在初始string1中):d”
当它不在dict()中时
发布于 2019-04-04 08:25:01
使用以下代码:
string1 = input("Enter a string:")
d = dict(enumerate(string1))
enter_value = input("Enter a value(should be in the initial string1):")
if enter_value in d.values():
print("Value found.")
else:
print("value not found.")该错误所做的是,如果值不正确,它会生成一个错误,但是您希望查看该值是否在字符串中,因此只需检查它,然后输出响应。
发布于 2019-04-04 08:25:23
您的代码运行正常。您正在询问enter_value是否在列表d.values()中,但如果不在,它就不会抛出错误,而是直接中断您的if语句,因为您没有索引或任何太复杂的东西。您可以使用如下所示的else:块来捕获此逻辑:
string1 = input("Enter a string:")
d = dict(enumerate(string1))
try:
enter_value = input("Enter a value(should be in the initial string1):")
if enter_value in d.values():
print("Value found.")
else:
print("Value not found.")
except:
print("There was an error!!")尽管对于这段特定的代码,我并不怀疑会有什么错误需要捕获(至少我能想到的是,我确信如果你足够努力,你可以通过XD破解它)
发布于 2019-04-04 08:39:57
正如前面提到的,if enter_value in d.values():将返回true或false,但是它不会引发异常,所以不要在这里使用try,因为它是不必要的。
此外,您可以简单地检查字符串中是否存在该值,而不是使用字典
string1 = input("Enter a string:")
enter_value = input("Enter a value(should be in the initial string1):")
if enter_value in string1:
print("Value found.")
else:
print("Value not found.")如果您想了解try/except,请查看此快速示例
try:
1 / 0
except ZeroDivisionError:
print('error, unable to divide by 0')https://stackoverflow.com/questions/55506072
复制相似问题