在我的代碼中,我試圖在計算收到的每個成績和他們的體重后顯示班級中成績最高的學生。出于某種原因,我知道 finalGrade 沒有定義。我將如何顯示成績最高的學生以及他們的最終成績?
def welcome():
print("Hello and Welcome to Top Students")
print("Our program lists your students and displays the highest of honors")
print("Let's get started\n")
def aveGrade():
quizGrade = int(input("What is the grade this student is receiving for their quiz?\n"))
partGrade = int(input("What is the grade this student is receiving for their prarticipation?\n"))
assignGrade = int(input("What is the grade this student is is receiving for their assignment?\n"))
finalGrade = ((quizGrade * .35) (partGrade * .15) (assignGrade * .50))
print("The final grade for this student is", finalGrade)
def main():
studentnames = ["Fred", "Daphne", "Velma", "Norville"]
for student in studentnames:
print("The current grade standing for", student, "are as follows:\n")
aveGrade()
print("The student with the highest final grade is", max(studentnames), "with a total of",max(finalGrade))
uj5u.com熱心網友回復:
變數只存在于范圍內。在這種情況下finalGrades,是在函式中定義的,aveGrade()并且只能從該函式中訪問。因此,您的主要功能并不“了解”該finalGrade變數。您可以finalGrade在全域范圍內宣告,然后在函式中為其賦值。
但更好的解決方案是從函式回傳值,如下所示:
def aveGrade():
quizGrade = int(input("What is the grade this student is receiving for their quiz?\n"))
partGrade = int(input("What is the grade this student is receiving for their prarticipation?\n"))
assignGrade = int(input("What is the grade this student is is receiving for their assignment?\n"))
finalGrade = ((quizGrade * .35) (partGrade * .15) (assignGrade * .50))
print("The final grade for this student is", finalGrade)
return finalGrade #Changed
然后像這樣使用它:
def main():
studentnames = ["Fred", "Daphne", "Velma", "Norville"]
for student in studentnames:
print("The current grade standing for", student, "are as follows:\n")
finalGrade = aveGrade() #Changed
print("The student with the highest final grade is", max(studentnames), "with a total of",max(finalGrade))
除了評論:
Velma 仍然是您的最高學生,因為您的學生和他們的最終成績沒有任何聯系。目前您只是在計算并回傳最終成績,但程式不知道它屬于學生。max(studentnames)將始終回傳 Velma,因為按字母順序 Velma 是最高值。也max(finalGrade)不會做太多,因為在您的 for 回圈的每次迭代中,finalGrade都會被回傳值覆寫,aveGrade()因此不是可以確定最大值的串列。一種方法是將學生及其最終成績保存為字典中的鍵值對
def main():
studentnames = ["Fred", "Daphne", "Velma", "Norville"]
studentGradesDic = {} #Added
for student in studentnames:
print("The current grade standing for", student, "are as follows:\n")
studentGradesDic[student] = aveGrade() #Changed
print("The student with the highest final grade is", list(studentGradesDic.keys())[list(studentGradesDic.values()).index(max(studentGradesDic.values()))], "with a total of",max(studentGradesDic.values())) #Changed
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519566.html
標籤:Python功能循环
