Python—返回值的函数

Python—返回值的函数,python,function,return,Python,Function,Return,我真的很难回答这个问题,有人能帮我写一个程序的代码吗?或者至少说我哪里做错了?我试了很多,但似乎没有达到预期的效果 以下是程序说明:Python 3程序,它包含一个函数,该函数接收三个测验分数,并将这三个分数的平均值返回到Python程序的主要部分,在那里打印平均分数。 我一直在尝试的代码: def quizscores(): quiz1 = int(input("Enter quiz 1 score: ")) quiz2 = int(input("Enter quiz 2 scor

我真的很难回答这个问题,有人能帮我写一个程序的代码吗?或者至少说我哪里做错了?我试了很多,但似乎没有达到预期的效果

以下是程序说明:Python 3程序,它包含一个函数,该函数接收三个测验分数,并将这三个分数的平均值返回到Python程序的主要部分,在那里打印平均分数。

我一直在尝试的代码:

def quizscores():
   quiz1 = int(input("Enter quiz 1 score: "))
   quiz2 = int(input("Enter quiz 2 score: "))
   quiz3 = int(input("Enter quiz 3 score: "))

   average = (quiz1 + quiz2 + quiz3) / 3
   print (average)
   return "average"
   quizscores(quiz1,quiz2,quiz3)

返回的是字符串而不是值。尝试
返回平均值
而不是
返回“平均值”

您的代码有一些问题:

  • 您的函数必须接受参数
  • 您必须返回实际变量,而不是变量的名称
  • 您应该询问这些参数,并在函数外部打印结果
试着这样做:

def quizscores(score1, score2, score3): # added parameters
    average = (score1 + score2 + score3) / 3
    return average # removed "quotes"

quiz1 = int(input("Enter quiz 1 score: ")) # moved to outside of function
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
print(quizscores(quiz1,quiz2,quiz3)) # print the result

首先,返回的是字符串,而不是变量。使用
返回平均值
而不是
返回“平均值”
。您也不需要函数中的
print()
语句。。。实际上,
print()
函数

如果以这种方式调用函数,则需要接受参数并请求函数外部的输入,以防止混淆。根据需要使用循环以重复使用函数,而不必每次都重新运行它。因此,最终的代码是:

def quiz_average(quiz1, quiz2, quiz3):
    average = (quiz1 + quiz2 + quiz3) / 3
    return average

quiz1 = int(input("Enter Quiz 1 score: "))
quiz2 = int(input("Enter Quiz 2 score: "))
quiz3 = int(input("Enter Quiz 3 score: "))

print(quiz_average(quiz1, quiz2, quiz3))  #Yes, variables can match the parameters

对于已经发布的解决方案,另一种解决方案是让用户输入他们所有的测试分数(用逗号分隔),然后使用求和法和除法将其相加并除以三,得到平均值

    def main():
        quizScores()

        '''Method creates a scores array with all three scores separated
        by a comma and them uses the sum method to add all them up to get
        the total and then divides by 3 to get the average.
        The statement is printed (to see the average) and also returned
        to prevent a NoneType from occurring'''

    def quizScores():
        scores = map(int, input("Enter your three quiz scores: ").split(","))
        answer = sum(scores) / 3
        print (answer)
        return answer

    if __name__ == "__main__":
        main()

您只是返回字符串
“average”
,正如@K.Menyah所说,您返回的是字符串文本,而不是变量
average
,只需删除引号即可。明白了,非常感谢!工作!我也发现了我的错误。非常感谢你!