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.
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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With