我不明白如何找到两个或多个数字的平均值。我尝试导入统计信息库,因此我可以使用平均值函数,但有些东西不起作用。
我不断收到最近一次调用的错误回溯。
import statistics
def findAverage(avg,avg2):
avg= int(input( 'Please enter a number'))
avg2 = int(input('Please enter a number'))
findAverage()
average=statistics.mean()
print(average)
用途statistics.mean(list_of_values)
如此
import statistics
def findAverage():
avg = int(input('Please enter a number1: '))
avg2 = int(input('Please enter a number2:'))
return statistics.mean([avg, avg2])
average = findAverage()
print(average)
您可以使用它找到任何数量数字的平均值:
# Python program to get average of a list
def Average(lst):
return sum(lst) / len(lst)
# Number List
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
# Printing average of the list
print("Average of the list =", round(average, 2))
我什至不明白你的代码是做什么的?
我想你想这样做吗?
def findAverage(avg,avg2):
return (avg+avg2)/2
avg= int(input( 'Please enter a number'))
avg2 = int(input('Please enter a number'))
print(findAverage(avg, avg2))
在定义函数和调用函数时,应该具有相同数量的参数。以及在列表中调用statistics.mean
函数:
import statistics
def findAverage():
avg1= int(input( 'Please enter a number'))
avg2 = int(input('Please enter a number'))
return statistics.mean([avg1, avg2])
findAverage()
Statistics.mean() 将list
作为输入数据。通过在调用后将列表传递到()
内来为其提供此数据,例如以下示例:
import statistics
data = [1,2,3] # a list of data
average = statistics.mean(data)
print(average)
这是您的修复示例,并附有注释来解释正在发生的事情:
import statistics
# anything inside the brackets below is a "parameter", which is
# information which can be passed to function when calling it.
# since this function finds the two numbers on its own, it doesn't
# need to be passed any information, so i've removed avg and avg2
def findAverage():
# the two lines below for collecting numbers are perfect,
# and don't need to be changed
avg = int(input( 'Please enter a number'))
avg2 = int(input('Please enter a number'))
# however since this is a function, we'll expect it to
# return the average value it calculated from the user input.
# we first put our data into a list like below:
data = [avg, avg2]
# then get the average by passing this data to the mean function
average = statistics.mean(data)
# then return this value so it can be printed out
return average
# we can now call our function, and print the result
print(findAverage())
首先,您需要提及值列表以statistics.mean([avg1,avg2])
。 如果您只想找到两个值的平均值,则无需使用它。 你用(num1+num2)/2
就足够了.
import statistics
def findAverage(num1,num2):
return statistics.mean([num1, num2])
num1= int(input( 'Please enter a number'))
num2= int(input('Please enter a number'))
result=findAverage(num1,num2)
print(result)