- The issue is,
user_day
is a string when entered as an input.
- Because it's a string, it doesn't meet any of the conditions, and therefore,
day_time
remains undefined.
- Wrap the input in a
try-except
block to check that the input is a proper data type. In this case, str
type that can be converted to an int
or float
.
- It must be converted to a
int
or float
depending on if you're going to accept only hours or fractional hours.
user_day
should be in a while True
loop to continue asking for a time until a valid numeric input is received.
- Finally, the code can be written more efficiently, by properly ordering the conditions from smallest to largest, for this case.
user_day
will trickle down to the correct condition.
while True:
try:
user_day = int(input("What's the hour on a 24-hour scale? "))
except ValueError: # checks for the correct data type; maybe someone will spell the hour
print('Please enter the hour as a numeric value')
if (user_day >= 24) or (user_day < 0): # 24 and over or less than 0 are invalid times
print('Please enter a valid time')
else:
break # break when there's valid input
if user_day < 12:
day_time = 'Morning'
elif user_day < 17:
day_time = 'Noon'
elif user_day < 20:
day_time = 'Evening'
else:
day_time = 'Night'
print(day_time)
- Return the indices of the bins to which each input value belongs.
- Use the value returned by
np.digitize
to index the correct value from day_time
import numpy as np
while True:
try:
user_day = int(input("What's the hour on a 24-hour scale? "))
except ValueError: # checks for the correct data type; maybe someone will spell the hour
print('Please enter the hour as a numeric value')
if (user_day >= 24) or (user_day < 0): # 24 and over or less than 0 are invalid times
print('Please enter a valid time')
else:
break # break when there's valid input
day_time = ['Morning', 'Evening', 'Noon', 'Night']
idx = np.digitize(user_day, bins=[12, 17, 20])
print(day_time[idx])