我真的在努力解决这个问题,任何人都可以帮我编写这个程序的代码吗?或者至少说我哪里出错了?我已经尝试了很多,但似乎无法获得所需的输出。
这是程序说明: 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)
答案 0 :(得分:1)
您将返回一个字符串而不是该值。请尝试使用return average
代替return "average"
。
答案 1 :(得分:1)
您的代码存在一些问题:
尝试这样的事情:
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
答案 2 :(得分: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
答案 3 :(得分:0)
已经发布的解决方案的另一个答案可能是让用户输入他们的所有测试分数(用逗号分隔),然后加起来并使用sum方法和除法符号除以3得到平均值。
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()