I'm trying to create a program where python will take multiple inputs to calculate the average of the input but it doesn't work though I search a lot but my problem differs from the rest as I use class. my code is as:
class my_class(object):
def __init__(self, number1, number2, number3):
self.number1 = number1
self.number2 = number2
self.number3 = number3
def defAvrg(self): # get the defAvrg of three numbers
return (self.number1 + self.number2 + self.number3)/3
#resulin = resulted / 3
#return resulted
my_class2 = my_class([float(input("Enter number %s: "%i)) for i in range(3)])
print(my_class2.defAvrg())
Objective: I want to take three input to find the average.
The __init__()
method for your class requires 3 positional parameters (in addition to self
) but your code passes only one - a list of the numbers entered by the user. You need to pass each of those numbers as a separate argument. You can use the *
operator to unpack the items in the list and pass these as separate arguments:
my_class2 = my_class(*[float(input("Enter number %s: "%i)) for i in range(3)])
That will solve the immediate problem, however, it would be more flexible if your class accepted a list of the numbers, binding that to an attribute of the object. Your average method would then calculate the average using the list, or it could simply use statistics.mean()
:
from statistics import mean
class my_class(object):
def __init__(self, numbers):
self.numbers = numbers
def defAvrg(self):
return mean(self.numbers)
The advantage of this approach is that you can collect an arbitrary number of values from the user.
You can call your Script with: scriptname n*<param^n>
So for You it would be python script.py number1 number2 number3
You can access them in Python with sys.argv[1-3]
, sys.argv[0]
is always the Script Name
您将列表作为单个参数传递,您需要扩展列表,以解压缩列表,您可以使用*
myClass(*list())
Such a solution works for me.
numbers = list()
for i in range(0, 3):
inputNr = int(input("Enter a number: "))
if(inputNr == -99):
break
numbers.append(inputNr)
#Then we take all of the numbers and calculate the sum and avg on them
sum = 0
for j, val in enumerate(numbers):
sum += val
print("The total sum is: " + str(sum))
print("The avg is: " + str(sum / len(numbers)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.