【问题标题】:How to calculate a grade for a class using lists and functions in Python如何使用 Python 中的列表和函数计算课程的成绩
【发布时间】:2015-11-27 07:26:34
【问题描述】:

我需要编写一个程序,根据以下输入和过程计算课程的成绩:

  1. 询问用户他们课程中的测试、作业、测验和实验室的数量。

  2. 询问用户是否存在与上述测试不同的重量,例如一个课程有 2 次测试,每一次占 12.5%,最后一次占 15%。

  3. 对于数字 > 0 a 的每个类别。提示用户输入 100% 中的加权百分比,所有类别的总和应为 100%!!!湾。获取类别的分数。 C。如果类别是实验室,则将所有分数相加。 d。否则,平均分数。 e.计算类别的加权平均值。

  4. 使用每个类别的加权平均值,计算课程中的成绩。

  5. 询问用户他/她是否想计算另一个班级的成绩。

  6. 如果用户回答是,则返回步骤 1。 7. 否则,结束程序。

我几乎完成了该程序并拥有了我的所有功能,但我很难将它们全部组合在一起并正常工作。我的第一个问题是合并步骤 5/6 并让 while 循环与其余代码一起工作。此外,我很难将实验室分数相加并将该值纳入加权平均值。

非常感谢任何帮助!

这是我的代码:

def main():
       inputList = get_user_input()
       average = get_scores(inputList)
       weightedAvgs = get_weightedavg(average, inputList)
       results = get_class_grade(weightedAvgs)

       ans = "yes"
       while(ans == "yes"):
            def get_user_input():
                    inputList = [] # initializes a list
            # Gets how many scores for each category the user would like to enter and adds value to a list
                    tests = int(input("How many tests scores would you like to enter? "))
                    inputList.append(tests)
                    assignments = int(input("How many assignment scores would you like to enter: "))
                    inputList.append(assignments)
                    quizzes = int(input("How many quiz scores would you like to enter? "))
                    inputList.append(quizzes)
                    labs = int(input("How many lab scores would you like to enter? "))
                    inputList.append(labs)
                    final = int(input("How many final scores would you like to enter? "))
                    inputList.append(final)

            # Gets the weight of each category if there are any scores to enter and adds the value to a list
                    if tests > 0:
                            testWeight = float(input("Enter the weight of tests: "))
                            inputList.append(testWeight)
                    else:
                            testWeight = 0
                    if assignments > 0:
                            assignmentWeight = float(input("Enter the weight of assignments: "))
                            inputList.append(assignmentWeight)
                    else:
                            assignmentWeight = 0
                    if quizzes > 0:
                            quizWeight = float(input("Enter the weight of quizzes: "))
                            inputList.append(assignmentWeight)
                    else:
                            quizWeight = 0
                    if labs > 0:
                            labWeight = float(input("Enter the weight of labs: "))
                            inputList.append(labWeight)
                    else:
                            labWeight = 0
                    if final > 0:
                            finalWeight = float(input("Enter the weight of the final: "))
                            inputList.append(finalWeight)
                    else:
                            finalWeight = 0

                    return(inputList)

            def get_scores(inputList):
            # Gets scores for each category & calculates avg for each category
                    average = []
                    testScoreList = []
                    tests2 = inputList[0]
                    for x in range(tests2):
                            testScore = float(input("Enter your test score: "))
                            testScoreList.append(testScore)
                    if tests2 == 0:
                            testAvg = 0
                    else:
                            testAvg = sum(testScoreList) / inputList[0]
                    average.append(testAvg)


                    assignmentScoreList = []
                    assignments2 = inputList[1]
                    for x in range(assignments2):
                            assignmentScore = float(input("Enter your assignment score: "))
                            assignmentScoreList.append(assignmentScore)
                    if assignments2 == 0:
                            assignmentAvg = 0
                    else:
                            assignmentAvg = sum(assignmentScoreList) / inputList[1]
                    average.append(assignmentAvg)


                    quizScoreList = []
                    quizzes2 = inputList[2]
                    for x in range(quizzes2):
                            quizScore = float(input("Enter your quiz score: "))
                            quizScoreList.append(quizScore)
                    if quizzes2 == 0:
                            quizAvg = 0
                    else:
                            quizAvg = sum(quizScoreList) / inputList [2]
                    average.append(quizAvg)


                    labScoreList = []
                    labs2 = inputList[3]
                    for x in range(labs2):
                            labScore = float(input("Enter your lab score: "))
                            labScoreList.append(labScore)
                    if labs2 == 0:
                            labSum = 0
                    else:
                            labSum = sum(labScoreList)
                    average.append(labSum)


                    finalScoreList = []
                    final2 = inputList[4]
                    for x in range(final2):
                            finalScore = float(input("Enter the score for your final: "))
                            finalScoreList.append(finalScore)
                    if final2 == 0:
                            finalAvg = 0
                    else:
                            finalAvg = sum(finalScoreList) / inputList[4]
                    average.append(finalAvg)


            def get_weighted_avg(average, inputList):
                    weightedAvgs = []

                    weightedTestAvg = average[0] * inputList[5]
                    weightedAvgs.append(weightedTestAvg)
                    print("Your weighted average is " + str(weightedTestAvg))

                    weightedAssignmentAvg = average[1] * inputList[6]
                    weightedAvgs.append(weightedAssignmentAvg)
                    print("Your weighted average is " + str(weightedAssignmentAvg))

                    weightedQuizAvg = average[2] * inputList[7]
                    weightedAvgs.append(weightedQuizAvg)
                    print("Your weighted average is " + str(weightedAssignmentAvg))

                    weightedLabSum = average[3] * inputList[8]
                    weightedAvgs.append(weightedLabSum)
                    print("The sum of your lab scores are " + str(weightedLabAvg))

                    weightedFinalAvg = average[4] * inputList[9]
                    weightedAvgs.append(weightedFinalAvg)
                    print("Your weighted average is " + str(weightedFinalAvg))

                    return(weightedAvgs)

            def get_class_grade(weightedAvgs):
                    grade = weightedAvgs[0] + weightedAvgs[1] + weightedAvgs[2] + weightedAvgs[3] + weightedAvgs[4]

                    if grade >= 90:
            finalGrade = "A"
                    elif grade >= 80:
                            finalGrade = "B"
                    elif grade >= 70:
                            finalGrade = "C"
                    elif grade >= 60:
                            finalGrade = "D"
                    else:
                            finalGrade = "F"

                    print("Your grade is " + finalGrade)
                    ans = (input("Would you like to calculate a grade for another class? "))
                    while(ans != "yes" and ans != "no"):
                            print("Please type yes or no")
                            ans = (input("Would you like to calculate a grade for another class? "))
    if ans == "no":
            exit()
main()

【问题讨论】:

  • 为什么要将函数嵌入到 while 循环中?
  • 您的代码复杂度确实让人难以阅读。请考虑以这样的方式重新组织您的代码,使主循环仅包含少量行,这些行可以调用其他函数。
  • @Oz123 我不确定如何合并 while 循环。我的想法是,如果我将 while 循环包裹在我的所有代码(包括函数)周围,只要条件为真,其中的所有内容都会运行。为了解决您的第二条评论,我很抱歉,但我不知道该怎么做。我是编程新手。
  • 对于初学者,您需要将函数定义移到 while 循环之外。首先定义函数,然后调用它们。请查看introductory Python tutorial; SO尝试教授该材料并不实际(或适当)。完成此操作后,查看其他人编写的代码以了解在 Python 中组织事物的常用方法也会有所帮助。

标签: python arrays function python-3.x computer-science


【解决方案1】:

我不会为您重新整理和重新组织您的代码,因为这是您真正需要解决的问题。相反,我将提供有关如何使用while-loops 的示例。

当真又破

使用while True,您可以连续运行以下代码。使用条件,您可以使用break 在该点退出循环

while True:
    # Will request a number and print it back to the user
    # If a valid entry is entered print and exit while loop
    # Otherwise while loop will continue
    user_input = input('Please enter a number: ')
    if user_input.isdigit(): # Checks if the input string is a number
        print('You entered {0}'.format(user_input))
        break # exit loop
    else:
        print('That is not a number')

同时递增

另一种方法是使用变量并在每次迭代后递增它。一旦计数器达到某个数字并伪造条件,则迭代完成后循环退出。

counter = 0
input_list = []
print('Please enter a valid non-number 5 times')
while counter < 5: # Exits when condition is false | counter >= 5
    user_input = input('Please enter a non-number: ')
    if not user_input.isdigit(): # Checks if the input string is a number
        input_list.append(user_input) # Add input to list
        counter += 1 # Increments counter by 1
    else:
        print("That's a number")

print(input_list)

同时使用布尔值并使用函数

您可以连续使用在 while 循环之外定义的函数,直到条件为假。在此示例中,每次都使用 double 函数,直到用户输入“q”或“Q”。变量是生成的True,它生成条件False 并结束循环。

def double(value):
    return value * 2

print('Find the result of double a value. Enter q to Quit')
exit_loop = False
while not exit_loop: # Same effect as while not False == while True
    user_input = input('Please enter a value: ')
    if user_input.lower() == 'q':
        exit_loop = True # exit loop
    elif user_input.isdigit(): # Checks if the input string is a number
        num = int(user_input)
        print(double(num))
    else:
        print(double(user_input))

旁注 在检查字符串的使用输入时,有几种方法可以做到这一点。这些示例均有效且不限于 -

if user_input.lower() == 'q':
if user_input == 'q' or user_input == 'Q':
if user_input in 'qQ':

【讨论】:

    猜你喜欢
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2019-05-11
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多