Python:ValueError '3' 不在列表中



我是编程新手,我不明白这个错误。我有一个程序,它可以根据给定的字母输入告诉你字母表的数字位置。如果输入不是字母表,它应该返回'不属于字母表'。然而,当我给出一个数字输入时,我得到一个ValueError。

我正在处理的代码:

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:")
Number0OfA = alphabets.index(myAlphabet)
for myAlphabet in alphabets:
if myAlphabet in alphabets:
print(myAlphabet ,'is the', Number0OfA, '. alphabet')
break
else:
print(myAlphabet , 'does not belong to the alphabet')

错误:

Exception has occurred: ValueError
'3' is not in list
File "C:Usersmepycodemain.py", line 4, in <module>
Number0OfA = alphabets.index(myAlphabet)

请帮忙就太好了。

。Index返回列表项的索引。所以alphabets.index("a")返回0。使用[int(myAlphabet)]代替。

你根本不需要循环:

import string
alphabet = string.ascii_lowercase + 'åäö' # long string with all letters
def print_in_alphabet(c, alphabet=alphabet):
# alphabet.index throws exception when value not found
try:
index = alphabet.index(c)
print(f'Letter {c} found at index {index} in alphabet')
except ValueError:
print(f'Letter {c} not found in alphabet')
print_in_alphabet('c') # Letter c found at index 2 in alphabet
print_in_alphabet('3') # Letter 3 not found in alphabet

失败的原因是,您的list不包含3,因此当index()试图获得3的位置时,它找不到它,因此说ValueError.
实际上不需要for循环。可以简单地使用in,如下所示:

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:")
if myAlphabet in alphabets:
print(myAlphabet ,'is the', alphabets.index(myAlphabet), '. alphabet')
else:
print(myAlphabet , 'does not belong to the alphabet')

但是,如果你仍然想使用for循环,方法如下:

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:")
if myAlphabet not in alphabets:
print (myAlphabet , 'does not belong to the alphabet')
else:
for index in range(len(alphabets)): 
if myAlphabet == alphabets[index]:
print(myAlphabet ,'is the', index, '. alphabet')
break

输出:

Enter the letter you are looking for in the alphabet:z
z is the 25 . alphabet

相关内容

最新更新