python: How can I print an alphabet from a list, given a number?

Viewed 156

Given a number from 1 to 26, I'm trying to return an alphabet in the corresponding position from a list.

Example:

Input = 1
Output = 'a'

I have tried the following:

user_input = int(input("Enter a number from 1 to 26 "))

for item in aplhabet:
    print(aplhabet.index(item[aplhabet]))

As expected that returns a type error because there are no integer values in my list.

What can I do to return an element from my list in which its position is equal to the users number input?

4 Answers

You can index a list by its index:

import string
alphabet = list(string.ascii_lowercase)

user_input = int(input("Enter a number from 1 to 26 "))

if 0 < user_input <= 26:
    print(alphabet[user_input - 1])
else:
    print("please input a number between 1 and 26")

Using ASCII conversion from integer to character, you can do it as follows,

n = int(input("Enter the number: "))
if(n > 0 and n < 27):
    print(chr(n + 96))
else: 
    print("Invalid input")

You can use indexing:

alphabets = 'abcdefghijklmnopqrstuvwxyz'

user_input = int(input("Enter a number from 1 to 26: "))
print(alphabets[user_input - 1])

Note that you need to subtract 1, since Python uses 0-based index.

There are 3 answers. All of them are perfectly working. The answers are already given in ASCII values and string. You can do it another way. Create a dictionary of number key and it's corresponding alphabet as value. Take the input. Print the value of of the input present in the dictionary. Your code:

d={1:"a",2:"b",3:"c",4:"d",5:"e",6:"f",7:"g",8:"h",9:"i",10:"j",11:"k",12:"l",13:"m",14:"n",15:"o",16:"p",17:"q",18:"r",19:"s",20:"t",21:"u",22:"v",23:"w",24:"x",25:"y",26:"z"}
x=int(input("Enter a number between 1 and 26= "))
print(d[x])
Related