You can use a while
loop and check for a valid input.
Try this code:
def main():
month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
total_rain = [0] * 12 # to store the total rain per month
sum = 0
for i in range(12):
rain = None
while not rain: # while invalid input
rain = input("Enter the total rain in " + month_names[i] + ": ")
if not rain.isnumeric(): # not number
print("Invalid!")
rain = None # retry input
total_rain[i] = int(rain)
sum += total_rain[i] #adding rain to sum
#printing result
s = "\n\nTotal Rainfall: " + str(sum) + "\nAverage monthly rainfall: " + str(sum/12) + "\nLowest Rainfall: " + str(min (total_rain))
+ " In month of " +str(month_names[total_rain.index(min(total_rain))])+"\nHighest Rainfall: " + str(max(total_rain))+" In month of " +
str(month_names[total_rain.index(max(total_rain))])
print(s)
return s
main()
Output
Enter the total rain in January: asdfad
Invalid!
Enter the total rain in January:
Invalid!
Enter the total rain in January: 12
Enter the total rain in February: 23
Enter the total rain in March: afad
Invalid!
Enter the total rain in March: 45
Enter the total rain in April: afcasdc
Invalid!
Enter the total rain in April: sc
Invalid!
Output 2
Enter the total rain in January: 1
Enter the total rain in February: 2
Enter the total rain in March: 3
Enter the total rain in April: 4
Enter the total rain in May: 5
Enter the total rain in June: 6
Enter the total rain in July: 7
Enter the total rain in August: 8
Enter the total rain in September: 9
Enter the total rain in October: 10
Enter the total rain in November: 11
Enter the total rain in December: 12
Total Rainfall: 78
Average monthly rainfall: 6.5
Lowest Rainfall: 1 In month of January
Highest Rainfall: 12 In month of December
CLICK HERE to find out more related problems solutions.