Reputation: 11
Okay something that should be easy is killing me. I have a list of days Monday-Sunday in a list and I need to ask a user to give a number 1-7 to show the corresponding day
I have this and it works but it seems like there should be a better way to get it done
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print('Enter a day number [1-7]: ', end="")
number=input()
if number == '1' :
print(days[0])
elif number == '2' :
print(days[1])
elif number == '3' :
print(days[2])
elif number == '4' :
print(days[3])
elif number == '5' :
print(days[4])
elif number == '6' :
print(days[5])
elif number == '7' :
print(days[6])
Upvotes: 1
Views: 70
Reputation: 975
As suggested by the @Jim Fasarakis-Hilliard You need to use try
and except
method to catch undesired input.
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print('Enter a day number [1-7]: ', end="")
try:
number=int(input('enter day'))
if number <= 7 and number > 0:
print(days[number-1])
else:
raise Exception
except ValueError:
print('must be an integer')
except Exception :
print('number must be below 7')
ValurError
will catch if number entered is not a number ,
and raise Exception
will catch if number entered is not in range 0<n<7
Upvotes: 0
Reputation: 16720
You could do this with a dictionary:
days = {'1': 'Monday',
'2': 'Tuesday',
'3': 'Wednesday',
'4': 'Thursday',
'5': 'Friday',
'6': 'Saturday',
'7': 'Sunday'}
number = input()
return days[number]
The merit of this, over using a simple list (which works well too since you're expecting integers) is that you might later want to accept inputs that are not numeric, like "one"
. You would just have to rename the dictionary's keys.
Upvotes: 1