我必须创建一个程序来收集成绩、计算平均值,然后打印最高和最低的平均值以及用户的姓名。我正在使用前一周作业中的代码,该代码接受用户输入并计算平均值,但我正在努力弄清楚如何从这些计算的平均值中检测高/低值。一旦检测到这些高/低值,我也不确定从哪里开始重新打印相关的名称信息。任何帮助将不胜感激!
def main():
numuser=eval(input("How many users are there?: "))
numgrade=eval(input("How many grades will there be for each user?: "))
usercount=0
gradecount=0
grade(numuser,numgrade,usercount,gradecount)
def grade(nu,ng,uc,gc):
name=[]
while uc <= nu:
first=input("Please enter the student's first name: ")
last=input("Please enter the student's last name: ")
name.append(last)
ID=input("Please enter the student's ID: ")
gradetot=0
total=[]
grades=[]
while gc < ng:
gradeval=eval(input("Please enter the grade: "))
total.append(gradeval)
gradetot=gradetot+gradeval
gc=gc+1
avg=gradetot/gc
grades.append(avg)
low=min(grades)
high=max(grades)
nu=nu-1
uc=uc+1
gc=0
print("The average grade for", first, last, ID, "is :", avg)
if uc>nu:
print("The lowest average is ", low, "and the highest average is", high)
main()
最佳答案
您必须将学生姓名及其平均成绩的数据存储在字典中。然后就可以使用字典方法进行检索
- 您在主循环中使用 in >= ,这会迭代更多次,这意味着要求用户输入更多记录
如果您想打印用户名及其成绩信息,则必须将它们存储在字典中
def main():
numuser=eval(input("How many users are there?: ")) numgrade=eval(input("How many grades will there be for each user?: ")) usercount=0 gradecount=0 grade(numuser,numgrade,usercount,gradecount)
def grade(nu,ng,uc,gc): dct={} while uc < nu: first=input("Please enter the student's first name: ") last=input("Please enter the student's last name: ") ID=input("Please enter the student's ID: ") gradetot=0
total=[] while gc < ng: gradeval=eval(input("Please enter the grade: ")) total.append(gradeval) average=[] gradetot=gradetot+gradeval average.append(gradetot) avg=gradetot/(gc+1) gc=gc+1 dct[first+last]=avg #Getting errors here with trying to find a mechanism to detect values from a calculated average #nu=nu-1 uc=uc+1 gc=0 print dct maxkey, maxvalue = max(dct.items(), key=lambda x:x[1]) print("The highest grade obtained by", maxkey, "is :",maxvalue )
""" nu=nu-1 uc=uc+1 gc=0
if uc>nu: print("The lowest average is ", low, " and the highest is ", high) #Need to print the names that go along with the grades
“”“
关于Python 3.6 : detect highest/lowest values from calculated averages from user input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47118232/