#python #arrays #loops #for-loop
#python #массивы #циклы #для цикла
Вопрос:
Я пытаюсь настроить for
цикл, в main()
котором проверяется, ввел ли пользователь число, символ или ничего. Я хочу получить результат Invalid input
, если они вводят что-либо, кроме числа.
В этой главе рассматриваются массивы, и я не могу понять, как это сделать.
Я пытался использовать isdigit()
, но не могу заставить его работать.
Это основной настроенный мной код, который работает нормально:
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):
total_rain[i] = int(input("Enter the total rain in " month_names[i] ": "))
sum = total_rain[i] #adding rain to sum
#printing result
print("nnTotal 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))]))
main()
Как я могу это сделать при использовании массивов? Я попытался настроить for
цикл следующим образом:
for total_rain[i] in i:
if total_rain[i].isdigit():
print("Invalid!")
continue
else:
break
Но это не работает.
Кто-нибудь может подтолкнуть меня в правильном направлении?
Ответ №1:
Вы можете использовать while
цикл и проверить правильность ввода.
Попробуйте этот код:
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 = "nnTotal 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()
Вывод
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!
Вывод 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
Комментарии:
1. Я изменил код и провел полный тест. Вывод выглядит правильно.
Ответ №2:
Получить в блоке try ..except:
try:
total_rain[i] = int(input("Enter the total rain in " month_names[i] ": "))
except ValueError:
print("Invalid!")