【问题标题】:Python- Function that returns a valuePython - 返回值的函数
【发布时间】:2016-03-22 23:12:11
【问题描述】:

我真的很想解决这个问题,谁能帮我为这个程序编写代码?或者至少说我哪里出错了?我尝试了很多,但似乎无法获得所需的输出。

这是程序描述: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)

【问题讨论】:

  • 你只是返回字符串"average"
  • 正如@K.Menyah 所说,您返回的是字符串文字而不是变量average,只需删除引号即可。
  • 知道了,非常感谢!

标签: python function return


【解决方案1】:

第一,您返回的是字符串,而不是变量。使用return average 而不是return "average"。您也不需要函数中的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

【讨论】:

    【解决方案2】:

    您返回的是字符串而不是值。试试return average 而不是return "average"

    【讨论】:

      【解决方案3】:

      您的代码存在一些问题:

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

      试试这样的:

      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
      

      【讨论】:

      • 成功了!也发现了我的错误。非常感谢!
      【解决方案4】:

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

          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()
      

      【讨论】:

        猜你喜欢
        • 2019-02-12
        • 2017-04-07
        • 2022-07-21
        • 2014-07-13
        • 2018-05-14
        • 1970-01-01
        • 2019-05-02
        • 2014-08-22
        • 1970-01-01
        相关资源
        最近更新 更多