Python: ValueError '3' 不在列表中

Python: ValueError '3' is not in list

我是编程新手,我不明白这个错误。我有一个程序可以根据给定的字母输入告诉您字母表的数字位置。如果输入不是字母表,它应该 return 'does not belong to the alphabet'。但是,我在输入数字时遇到 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:\Users\me\pycode\main.py", line 4, in <module>
    Number0OfA = alphabets.index(myAlphabet)

任何帮助都会很棒。

.index returns 列表条目的索引。所以 alphabets.index("a") returns 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