Python运行出现ValueError: '3' is not in list错误,字母位置查询代码求解
问题排查与解决方案
核心报错原因
list.index()方法特性:该方法在传入值不存在于目标列表中时,会直接抛出ValueError终止程序运行。输入的数字3不在预设的字母表列表内,且代码在未做存在性校验的前提下就直接调用了alphabets.index(myAlphabet),程序还未走到后续判断逻辑就直接崩溃。- 逻辑冗余错误:代码中后续的for循环完全多余,已经获取到了用户输入的内容,无需遍历整个字母表;且循环中重新对
myAlphabet变量赋值,会覆盖原始用户输入,逻辑完全偏离需求。
修正后代码
alphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','å','ä','ö'] myAlphabet = input("Enter the letter you are looking for in the alphabet:") # 先做存在性校验,避免触发index方法的报错 if myAlphabet in alphabets: # 列表索引默认从0开始,输出1开头的位置需要+1 position = alphabets.index(myAlphabet) + 1 print(myAlphabet ,'is the', position, '. alphabet') else: print(myAlphabet , 'does not belong to the alphabet')
可选优化
如果需要支持用户输入大写字母也能正常识别,可将获取输入的代码修改为:myAlphabet = input("Enter the letter you are looking for in the alphabet:").lower()
内容的提问来源于stack exchange,提问作者Gunther54
相关产品推荐
相关产品推荐

