Skip to main content
 首页 » 编程设计

python之Try/Except,不返回 except

2025年05月04日15soundcode

我正在尝试使用 try 和 except 一些代码。我已经能够让代码的 try 部分正常工作,但不是 except 部分。我正在使用 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() 中时,我编写的代码会产生正确的响应。但显示: "请输入一个值(应在初始字符串1):d"

当不在dict()中时

请您参考如下方法:

使用代码:

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.") 

该错误的作用是,如果值不正确但您想查看该值是否在字符串中,它会产生错误,因此只需检查它然后发出响应即可。