Python 3- Assign grade

落爺英雄遲暮 提交于 2019-12-02 23:41:30

问题


I am trying to write a program that reads a list of scores and then assigns a letter grade based on the score. Define a function to prompt user to enter valid scores until they enter a sentinel value -999. The function should create a list and return the list. I keep getting my sentinel value -999 into my list. How do i prevent this?

def main():
   grade = getScore()
   abcGrade = getGrade(grade)
   print(grade, "is an", abcGrade)


def getScore():
   grade = []
   while grade != -999:
      grade = int(input("Enter grades (-999 ends): "))
   return grade

def getGrade(grade):
   best = 100
   if grade >= best - 10:
      return 'A'
   elif grade >=  best - 20:
      return 'B'
   elif grade >= best - 30:
      return 'C'
   elif grade >= best - 40:
      return 'D'
   else:
      return 'F'

main()

回答1:


That's what you're looking for:

from statistics import mean

def main():
   grades = getScores()
   grade = mean(grades)
   abcGrade = getGrade(grade)
   print(grade, "is an", abcGrade)


def getScores():
   grades = []
   while True:
      grade = int(input("Enter grades (-999 ends): "))
      if grade == -999: return grades
      grades.append(grade)

def getGrade(grade):
   best = 100
   if grade >= best - 10:
      return 'A'
   elif grade >=  best - 20:
      return 'B'
   elif grade >= best - 30:
      return 'C'
   elif grade >= best - 40:
      return 'D'
   else:
      return 'F'

main()

I've done as little modifications as I can. You must get all the grades and take the mean. The problem in your code was that it didn't return any value or append() to the list.




回答2:


In this piece of code, you're not adding the value entered by the user to the list grade; you're re-defining grade so it's no longer a list but instead an integer:

def getScore():
   grade = []
   while grade != -999:
      grade = int(input("Enter grades (-999 ends): "))
   return grade

This wouldn't fly in strict, type-safe languages but, hey, it's python :)

To fix it, rename the list (grades would be an intuitive name) and use append() to add the value of grade to it. Then, return grades, not grade to get a list back.



来源:https://stackoverflow.com/questions/36535894/python-3-assign-grade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!