I'm new to programming and I don't understand this error. I have a program that is supposed to tell you the numerical position of an alphabet from a given letter input. If the input is not an alphabet it should return 'does not belong to the alphabet'. However I'm getting a ValueError when giving a number input.
The code I'm working on:
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')
The error:
Exception has occurred: ValueError
'3' is not in list
File "C:\Users\me\pycode\main.py", line 4, in <module>
Number0OfA = alphabets.index(myAlphabet)
Any help would be great.
The reason for failure is, your list
does not contain 3
, and hence when index()
tries to get the location of 3
it does not find it and hence says ValueError
.
There's actually no need of a for
loop. It can simply be done using in
as below:
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')
However if you still want to use a for loop, below is the way:
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
Output:
Enter the letter you are looking for in the alphabet:z
z is the 25 . alphabet