Home > other >  Simple "get letter of the alphabet via number" code doesn't work for "z"?
Simple "get letter of the alphabet via number" code doesn't work for "z"?

Time:10-25

I'm newly learning Python for school, I have wrote this code as training; it works fine except for the last letter "z".

Ther code is this:

alpha = "abcdefghijklmnopqrstuvwxyz"

letter = int(input('Input number of letter needed from alphabet (between 1 and 26): '))

if 0 < letter < len(alpha):
    print(alpha[letter - 1])

elif letter <= 0:
    print ('Number is smaller than number of letters in the alphabet.')

elif letter > len(alpha):
    print ("Number is larger than number of letters in the alphabet")

It works fine, but when I enter "26" which is for "z", it gives me null instead of an error or "z". Test it here.

CodePudding user response:

You must include "=" in fisrt if statement:

alpha = "abcdefghijklmnopqrstuvwxyz"

letter = int(input('Input number of letter needed from alphabet (between 1 and 26): '))

if 0 < letter <= len(alpha):
 print(alpha[letter - 1])

elif letter <= 0:
 print ('Number is smaller than number of letters in the alphabet.')

elif letter > len(alpha):
 print ("Number is larger than number of letters in the alphabet")

CodePudding user response:

you have to change if 0 < letter < len(alpha): to if 0 < letter <= len(alpha): as this drops the case where letter = len(alpha), which is for the letter 'z'

bonus: you can write a one-liner for it if you know what ASCII is (assuming the input is valid though)

print(chr(96   int(input())))
  • Related