Я создал программу, которая вычисляет среднее значение студента, и я хочу, чтобы входные данные создавались на основе пользовательского ввода, например: если пользователь вводит 5, он создает 5 входных данных.
print('Average of students')
def student_average():
while True:
try:
# I want to create inputs depending on the user's input in the following question:
number_of_qualifications = int(input('What is the number of qualifications?: '))
qualification_1 = float(input('What is the first qualification?: '))
qualification_2 = float(input('What is the second qualification?: '))
qualification_3 = float(input('What is the third qualification?: '))
qualification_4 = float(input('What is the fourth qualification?: '))
break
except:
print('This is not an option')
sum = (qualification_1 + qualification_2 + qualification_3 + qualification_4)
average = (sum / 4)
print(average)
student_average()






Вам нужно использовать петлю. Я удалил try/except, вы можете добавить его обратно, если хотите.
def student_average():
number_of_qualifications = int(input('What is the number of qualifications?: '))
sumx = 0
for _ in range(number_of_qualifications):
sumx += float(input('What is the next qualification?: '))
return sumx / number_of_qualifications
print(student_average())
могу я узнать, как вы реализуете try-кроме цикла for? Если возникает исключение, цикл все равно увеличивается на 1, поэтому 1 точка данных теряется, поэтому я не могу решить эту проблему.
Вы можете поместить try/except внутрь цикла for.
не могли бы вы показать мне, как, пожалуйста? Попробуйте с 5 входами: 10, 20, 30, аа (исключение), 40, 50. Среднее должно быть 30, но я не могу ввести последний (50)
while True/try/input/break/except/print.
это решение - цикл while, а не цикл for. Я думаю, что это возможно только в цикле while
Я изменил ваши коды, поэтому функция try-except сохранена.
def student_average():
total, c = 0,0
number_of_qualifications = int(input('What is the number of qualifications?: '))
while True:
try:
# I want to create inputs depending on the user's input in the following question:
total += float(input(f'{c+1} What is the qualification?: '))
c += 1
if c == number_of_qualifications:
break
except:
print('This is not an option')
average = (total / number_of_qualifications)
print(average)
print('Average of students')
student_average()
Выход:
Average of students
What is the number of qualifications?: 3
1 What is the qualification?: 4
2 What is the qualification?: 5
3 What is the qualification?: a
This is not an option
3 What is the qualification?: 6
5.0
Пожалуйста, не используйте «сумму» в качестве переменной, потому что это зарезервированное слово Python. Если он использовался ранее, вам необходимо перезапустить ядро.
def student_average():
cnt = 1
total_list = []
number_of_qualifications = int(input('What is the number of qualifications?: '))
while len(total_list) < number_of_qualifications:
try:
# I want to create inputs depending on the user's input in the following question:
total_list.append(float(input(f'{cnt}. What is the qualification?: ')))
cnt += 1
except:
print('This is not an option')
return (sum(total_list) / number_of_qualifications)
print('Average of students =', student_average())
Выход
What is the number of qualifications?: 5
1. What is the qualification?: 10
2. What is the qualification?: 20
3. What is the qualification?: 30
4. What is the qualification?: aa
This is not an option
4. What is the qualification?: 40
5. What is the qualification?: 50
Average of students = 30.0
Вы можете создать цикл для введенных number_of_qualifications и сохранить квалификации в массиве.