我想让我的程序从任意数量的学生中获取任意数量的分数,并对它们进行计算。
student_number = 1
try:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
except:
print("The score entered is not a number. Please enter it again.")
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
while score != -1:
try:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
except:
print("The score entered is not a number. Please enter it again.")
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
more_student = input("Any more student? (Yes or No): ")
while more_student == "Yes":
student_number = student_number + 1
try:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
except:
print("The score entered is not a number. Please enter it again.")
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
while score != -1:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
more_student = input("Any more student? (Yes or No): ")
print("done")
我不想打印("done"),我想以某种方式获取我收到的每个输入,并能够按学生将其分开,例如输出:
学生_有4个分数。他们的平均分是_。学生_有3分。他们的平均分是_。
我会用字典我猜?这将允许收集每个学生的数据,即。
scores = {}
student = input("Student ? ") # Ask for student
if(student not in scores.keys()): # Create new student if necessary
scores[student] = []
score = int(input("Score ? ")) # Generate & store score for the student
scores[student].append(score)
然后为每个学生计算分数的平均值…这么多的可能性。对我来说最简单的一个:
for student, score_list in scores.items():
nb_scores = len(score_list)
mean_score = sum(score_list)/len(score_list)
print("Student {} had {} scores, with a mean of {}". format(student, nb_scores, mean_score))
我刚刚为你的另一个被删除的问题输入了这个——它看起来和这个问题是相同的基本问题。
简单地说(我看到这个版本的问题的公认答案已经在做了),方法是使用两个嵌套循环,当需要进入外部循环时打破它们。
scores = []
while True:
scores.append([])
while True:
try:
score = int(input(
f"Please enter Student {len(scores)}'s score (-1: Exit): "
))
if score == -1:
break
scores[-1].append(score)
except ValueError:
print("The score entered is not a number. Please enter it again.")
if input("Any more student? (Yes or No): ").lower() != "yes":
break
print(scores)
Please enter Student 1's score (-1: Exit): 78
Please enter Student 1's score (-1: Exit): 34
Please enter Student 1's score (-1: Exit): -1
Any more student? (Yes or No): yes
Please enter Student 2's score (-1: Exit): 45
Please enter Student 2's score (-1: Exit): -1
Any more student? (Yes or No): No
[[78, 34], [45]]
我包含了两个当输入-1时中断的无限循环。hashmap用于每个Student ID都是一个键,并且在第二个循环执行时使用一个空数组初始化,该数组存储标记。
marks = {}
while True:
i = int(input("Enter Student ID or press -1 to exit"))
if i == -1:
break
else:
marks[i] = []
while True:
x = int(input("Enter Mark or press -1 to exit"))
if x!=-1:
marks[i].append(x)
else:
break
for i in marks.keys():
count = len(marks[i])
avg = sum(marks[i])/count
print("Student {} has {} scores. Their average is {}".format(i, count, avg))