Reputation: 91
How do you get a list to correspond with a user input. If I had a list like:
month_lst = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
How do I get an input of 1 to return 'January' as the answer?
input('Enter the number to be converted: ')
Also the input needs to check with the list to make sure it is within 1-12, so inputing 15 would read an error message.
Upvotes: 9
Views: 18743
Reputation: 2355
I know it is very old question. But have I found a very simple solution.
import calendar
def get_month_name(month_number):
try:
return calendar.month_name[month_number]
except IndexError:
print("'{}' is not a valid month number".format(month_number))
Upvotes: 1
Reputation: 861
The calendar library can provide what you want, see the documentation at http://docs.python.org/2/library/calendar.html
calendar.month_name[month_number] #for the full name
or
calendar.month_abbr[month_number] #for the short name
Upvotes: 15
Reputation: 11
month_lst = ['January', 'Feburary', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
try:
month = int(input('Enter the number to be converted: '))
if month < 1 or month > 12:
raise ValueError
else:
print(month_lst[month - 1])
except ValueError:
print("Invalid number")
Upvotes: 1
Reputation: 881303
You can get input from the user with input()
or raw_input()
, depending on your python version (the latter for Python 2.x).
You can turn the string that gives you into an integer with int()
.
Finally, you can look up the strings in your list with month_lst[some_integer]
where some_integer
is one less than the integer you got from the user.
Upvotes: 0