【问题标题】:Having trouble on this Python homework problem在这个 Python 作业问题上遇到麻烦
【发布时间】:2022-05-07 20:04:55
【问题描述】:

问题:编写一个程序,不断地询问用户一个考试分数,该分数以 0 到 100 范围内的整数百分比形式给出。如果输入了除 -1 以外的范围之外的值,则打印出错误并提示用户再试一次。计算输入的所有有效成绩的平均值以及每个字母等级类别中的总成绩如下:90 到 100 是 A,80 到 89 是 B,70 到 79 是 C,60 到 69 是D,而 0 到 59 是 F。使用负分作为标记值来指示输入的结束。 (负值仅用于结束循环,所以不要在计算中使用它。)例如,如果输入是。

#Enter in the 4 exam scores
g1=int(input("Enter an exam score between 0 and 100 or -1 to end: "))
g2=int(input("Enter an exam score between 0 and 100 or -1 to end: "))
g3=int(input("Enter an exam score between 0 and 100 or -1 to end: "))
g4=int(input("Enter an exam score between 0 and 100 or -1 to end: "))

total =(g1 + g2 + g3 + g4)

while g1 is range(0,100):
    continue
else:
    print("Sorry",g1,"is not in the range of 0 and 100 or -1. Try again!")

while g2 is range(0,100):
    continue
else:
    print("Sorry",g2,"is not in the range of 0 and 100 or -1. Try again!")

while g3 is range(0,100):
    continue
else:
    print("Sorry",g3,"is not in the range of 0 and 100 or -1. Try again!")

while g4 is range(0,100):
    continue
else:
    print("Sorry",g4,"is not in the range of 0 and 100 or -1. Try again!")

#calculating Average
def calc_average(total):
    return total/4

def determine_letter_grade(grade):
    if 90 <= grade <= 100:
        1 + TotalA
    elif 80 <= grade <= 89:
        1 + TotalB
    elif 70 <= grade <= 79:
        1 + TotalC
    elif 60 <= grade <= 69:
        1 + TotalD
    else:
        1 + TotalF

grade=total
average=calc_average

#printing the average of the 4 scores
print("You entered four valid exam scores with an average of: " + str(average))
print("------------------------------------------------------------------------")
print("Grade Distribution:")
print("Number of A's: ",TotalA)
print("Number of B's: ",TotalB)
print("Number of C's: ",TotalC)
print("Number of D's: ",TotalD)
print("Number of F's: ",TotalF)

给我的示例输出:

Enter an exam score between 0 and 100 or -1 to end: 88.64 
Enter an exam score between 0 and 100 or -1 to end: 103
Sorry, 103 is not in the range of 0 and 100 or -1. Try Again! 
Enter an exam score between 0 and 100 or -1 to end: 99.10 
Enter an exam score between 0 and 100 or -1 to end: 71.52
Enter an exam score between 0 and 100 or -1 to end: 73
Enter an exam score between 0 and 100 or -1 to end: -1
You entered 4 valid exam scores with an average of 83.07.

Grade Distribution
Number of A’s = 1
Number of B’s = 1
Number of C’s = 2
Number of D’s = 0
Number of F’s = 0

注意:这是我的第一堂计算机科学课,所以我确信有一个明显的解决方法是我想念的,但我很感激我能得到的任何帮助

【问题讨论】:

  • 只有4个考试成绩吗?或者任意数量的考试成绩?
  • 很抱歉,您的解决方案存在很多问题。看来您还没有完全理解这个问题或如何为它编写 Python 解决方案 - 首先,您的解决方案假定应该始终有 4 个输入,但如果只有 3 个呢?还是5?试着想象一下没有代码的任务,想象有人问你分数,把它们加起来,直到你告诉他们你完成了,然后计算结果。如果您以微小的步骤向自己描述该过程,那么您将更接近您应该编写的代码,而不是与示例输出大致对应的代码行。
  • 只有 4 个考试成绩,是的,这是我在尝试完成硬件问题时最失落的一次。

标签: python python-3.x


【解决方案1】:

这是我的演练解释:

所以,程序应该询问用户他们得到了什么分数直到他们说他们得到了-1 的分数,然后你给他们他们的结果。要循环直到他们给出-1,我们可以使用while 循环:

inp = float(input("Enter an exam score between 0 and 100 or -1 to end: ")) # Get input
grades = []
while inp > -1: # Loop until user gives a score of -1
    if inp >= 0 and inp <= 100: # Check if valid grade
        grades.append(inp) # Add grade to grades list
        inp = float(input("Enter an exam score between 0 and 100 or -1 to end: ")) # Ask again
    else:
        print("Sorry", inp, "is not in the range of 0 and 100 or -1. Try again!") # Invalid grade

# ANALYSIS OF GRADES

# Format first line of output - the first str(len(grades)) give the amount of grades they entered,
# and the str(sum(grades) / len(grades)) gives the average of the grades list.
print("You entered", str(len(grades)), "valid exam scores with an average of", str(sum(grades) / len(grades)))

print("Grade Distribution:")
print("Number of A's =", str(sum(90 <= g <= 100 for g in grades)) # I am using a very short notation
print("Number of B's =", str(sum(80 <= g <= 89 for g in grades)) # here - this is basically counting
print("Number of C's =", str(sum(70 <= g <= 79 for g in grades)) # the number of grades that are
print("Number of D's =", str(sum(60 <= g <= 69 for g in grades)) # a valid value based on the checks
print("Number of F's =", str(sum(0 <= g <= 59 for g in grades)) # I am making.

希望我的 cmets 可以帮助您弄清楚我的代码中发生了什么!

【讨论】:

    【解决方案2】:

    这里你的问题可以分成几个部分,

    1. 从用户那里获取考试数量
    2. 从用户那里获得这些考试的有效输入
    3. 计算所有考试的平均值
    4. 计算成绩分布
    5. 如果用户输入为-1则退出

    以下代码遵循所有这些步骤

        #calculating Average
        def calc_average(scores):
                return sum(scores)/len(scores)
    
    
    
        grade_dist = {
        (90, 101):'A',
        (80,90):'B',
        (70, 80):'C',
        (59, 70):'D',
        (0,59):'F'
        }
    
        def get_grade_freq(scores):
            grades = {'A':0, 'B':0, 'C':0, 'D':0, 'F':0}
    
            for score in scores:
              for k, v in grade_dist.items():
                if score in range(k[0], k[1]):
                  grades[v]+=1
    
            print("Grade distributions")
    
            for grade, number in grades.items():
                print("Number of {}’s = {}".format(grade, number))
    
    
    
        def get_scores(n):
            scores = []
            cond = True
            while cond and n>0:
              score = int(input("Enter an exam score between 0 and 100 or -1 to end : "))
              if score==-1:
                cond=False
                return -1
              if score not in range(0,101):
                  print("Sorry, {} is not in the range of 0 and 100 or -1. Try Again!".format(score))
              if score in range(0,101):
                scores.append(score)
                n-=1
            return scores
    
        def main():
            n = int(input('total number of exams ' ))
    
            scores = get_scores(n)
            if scores == -1:
                exit(-1)
    
            average = calc_average(scores)
    
            print("You entered {} valid exam scores with an average of {}.".format(n, average))
    
            get_grade_freq(scores)
    
    
        if __name__=='__main__':
            main()
    

    【讨论】:

      【解决方案3】:

      当您有多个类似事物的实例需要处理(得分范围、总计数)时,您必须尝试使用​​多值结构而不是单个变量。 Python 的列表和字典旨在收集多个条目作为位置列表或键控索引(字典)。

      这将使您的代码更加通用。当您操纵概念而不是实例时,您就会知道自己走在了正确的轨道上。

      例如:

      grading = [(None,101),("A",90),("B",80),("C",70),("D",60),("F",0)]
      scores  = {"A":0, "B":0, "C":0, "D":0, "F":0}
      counts  = {"A":0, "B":0, "C":0, "D":0, "F":0}
      while True:
          input_value = input("Enter an exam score between 0 and 100 or -1 to end: ")
          value       = int(input_value)
          if value == -1: break
          score = next((s for s,g  in grading if value >= g),None)
          if score is None:
              print("sorry ",input_value," is not -1 or in range of 0...100")
              continue
          scores[score] += value
          counts[score] += 1
      
      inputCount = sum(counts.values())
      average    = sum(scores.values())//max(1,inputCount)  
      print("")
      print("You entered", inputCount, "valid exam scores with an average of: ", average)
      print("------------------------------------------------------------------------")
      print("Grade Distribution:")
      for grade,total in counts.items():
          print(f"Number of {grade}'s: ",total)
      

      grading 列表包含成对的分数字母和最小值(以元组形式)。这样的结构将允许您通过查找值低于或等于输入值的第一个条目并使用相应的字母来将等级值转换为评分字母。

      相同的列表用于验证输入值,方法是在 100 之后策略性地放置一个 None 值,并且没有低于零的值。 next() 函数将为您执行搜索并在不存在有效条目时返回 None。

      您的主程序循环需要继续,直到输入值为 -1,但它至少需要遍历输入一次(典型的重复直到结构,但 Python 中只有 while)。所以while 语句将永远循环(即while True)并且需要在满足退出条件时任意中断。

      要累积分数,字典 (scores) 比列表更适合,因为字典允许您使用键(分数字母)访问实例。这使您可以跟踪单个变量中的多个分数。计算每个分数的输入数也是如此。

      要获得最后的平均值,您只需将 scores 字典的值分数相加,然后除以您添加到 counts 字典的分数计数。

      最后要打印分数统计摘要,您可以再次利用字典结构,只需为所有分数字母和总数编写一个通用打印行。

      【讨论】:

        【解决方案4】:

        这可能对你有用:

        scores = {
            "A": 0,
            "B": 0,
            "C": 0,
            "D": 0,
            "F": 0,
        }
        total = 0
        count = 0
        
        input_value = 0
        
        while (input_value != -1) and (count < 4):
            input_value = int(input("Enter an exam score between 0 and 100 or -1 to end: "))
            if 0 <= input_value <= 100:
                total += input_value
                count += 1
                if input_value >= 90:
                    scores["A"] += 1
                elif input_value >= 80:
                    scores["B"] += 1
                elif input_value >= 70:
                    scores["C"] += 1
                elif input_value >= 60:
                    scores["D"] += 1
                else:
                    scores["F"] += 1
            else:
                print("Sorry", input_value, "is not in the range of 0 and 100 or -1. Try again!")
        
        print("You entered {} valid exam scores with an average of: {}".format(count, total / count))
        print("------------------------------------------------------------------------")
        print("Grade Distribution:")
        print("Number of A's: ", scores['A'])
        print("Number of B's: ", scores['B'])
        print("Number of C's: ", scores['C'])
        print("Number of D's: ", scores['D'])
        print("Number of F's: ", scores['F'])
        

        【讨论】:

        • 纠错在哪里(确保值是-11-100之间)??
        • @AyushGarg 为发现干杯!
        • 非常感谢您的回复。它起初有效,但在我输入四个有效分数后,它会不断要求更多。不知道是什么原因造成的。
        • @Mitchellsullivan 该解决方案适用于任意数量的条目。如果您将while input_value != -1: 更改为while (input_value != -1) and (count &lt; 4):,并进行一些小调整,则可以将其限制为 4 个条目。我已将答案修改为最多仅支持 4 个
        • 为什么?在用户输入 -1 之前,这段代码应该是无限的!
        猜你喜欢
        • 2020-11-02
        • 2020-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多