#python #list
#python #Список
Вопрос:
Я обрабатываю целочисленные входные данные от пользователя и хотел бы, чтобы пользователь сообщал, что они завершены с вводом, введя ‘q’, чтобы показать, что они завершены с их вводом.
Вот мой код до сих пор: (Все еще очень новичок, так что не слишком меня раздражайте)
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num = int(input("Enter a number: "))
while num != "q":
num = int(input("Enter a number: "))
count = 1
total = num
del record[-1]
print (num)
print("The average of the numbers is", total / count)
main()
Любая обратная связь полезна!
Комментарии:
1. Взгляните на realpython.com/python-while-loop /…
Ответ №1:
Вероятно, вы получаете a ValueError
при запуске этого кода. Это способ python сообщить вам, что вы ввели значение в функцию, которая не может обрабатывать этот тип значения.
Для получения более подробной информации ознакомьтесь с документами по исключениям.
В этом случае вы пытаетесь ввести букву «q» в функцию, которая ожидает int()
в строке 6. Подумайте о int()
машине, которая обрабатывает только целые числа. Вы только что попытались вставить букву в машину, которая не оборудована для обработки букв, и вместо того, чтобы взорваться, она отклоняет ваш ввод и ставит разрывы.
Вероятно, вы захотите обернуть преобразование из str
в int
в try:
оператор для обработки исключения.
def main():
num = None
while num != "q":
num = input("Enter number: ")
# try handles exceptions and does something with them
try:
num = int(num)
# if an exception of "ValueError" happens, print out a warning and keep going
except ValueError as e:
print(f'that was not a number: {e}')
pass
# if num looks like an integer
if isinstance (num, (int, float)):
print('got a number')
Тест:
Enter number: 1
got a number
Enter number: 2
got a number
Enter number: alligator
that was not a number: invalid literal for int() with base 10: 'alligator'
Enter number: -10
got a number
Enter number: 45
got a number
Enter number: 6.0222
that was not a number: invalid literal for int() with base 10: '6.0222'
Я оставлю это вам, чтобы выяснить, почему 6.02222 «не было числом».
Ответ №2:
вы должны изменить свой код как можно меньше…
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num.append(input("Enter a number: "))
while num[-1] != "q":
num.append(input("Enter a number: "))
count = 1
try:
total = int(num[-1])
except ValueError as e:
print('input not an integer')
break
print (num)
print("The average of the numbers is", total / count)
main()
Ответ №3:
Вы можете попробовать это так:
def main():
num_list = [] #list for holding in user inputs
while True:
my_num = input("Please enter some numbers. Type 'q' to quit.")
if my_num != 'q':
num_list.append(int(my_num)) #add user input as integer to holding list as long as it is not 'q'
else: #if user enters 'q'
print(f'The Average of {num_list} is {sum(num_list)/len(num_list)}') #calculate the average of entered numbers by divide the sum of all list elements by the length of list and display the result
break #terminate loop
main()