-1
line 89, in main
    statSet.addNumber(int(n))
ValueError: invalid literal for int() with base 10: ''

当我输入我的代码时:

#statistics calc

from math import sqrt

#def stat set funk.

class StatSet:
    def __init__(self):
        self.data = 0

#def get data

    def getData(self):
        return self.data

#def add num.

    def addNumber(self,x):
        if isinstance(x,(int,float)):
            data = self.data
            data.append(x)
            self.data = data
            return self
#def mean funk.

    def mean(self):
        nums = self.data

#check (if) cond.

        if len(nums)>0:
            return sum(nums)/len(nums)
        else:
            return 0

#def med funk.

    def median(self):
        nums = self.data
        nums.sort()
        length = len(nums)
        remainder = length%2
        med = 0

#if to check length

        if length == 0:
            return Non
        elif remainder ==0:
            med = (nums[length//2] + nums[length//2-1])/2
        else:
            med = nums[length//2]
        return med

#def funk stdDev

    def stdDev(self):
        data = self.data
        N = self.count()
        mean = self.mean()
        devSum = 0

        for i in range(N):
            devSum = devSum + (data[i] - mean)**2
        return sqrt(devSum)

#def count funk.

    def count(self):
        count = len(self.data)
        return count

#def min funk.

    def min(self):
        nums = self.data
        nums.sort()
        minNum = nums[0]
        return minNum

#def max funk.

    def max(self):
        nums = self.data
        nums.sort()
        maxNum = nums[-1]
        return maxNum

#main prog.

def main():

        print("Program test of StatSet class")

#class constructor

        statSet = StatSet()
        while True:
            n = input("Enter a number (to quit): ")
            if n =="":
                break
#call addnumber funk.

        statSet.addNumber(int(n))

        print("Data: ", statSet.getData())
        print("Mean: ", statSet.mean())
        print("Median: ", statSet.median())
        print("Standard deviation: ", statSet.stdDev())
        print("Min: ", statSet.min())
        print("Max: ", statSet.max())
        print("Data: ", statSet.getData())
        print("Count: ", statSet.count())

        if __name__ == '__main__':
            main()
main()
4

2 回答 2

0

终于修好了。问题出在我的初始值中:

#def stat set funk.

class StatSet:
    def __init__(self):
        self.data = []

#def get data

    def getData(self):
        return self.data

#def add num.

    def addNumber(self,x):
        if isinstance(x,(int,float)):
            self.data.append(x)
            return self
于 2021-11-13T00:10:42.587 回答
0

问题出在这个循环中:

    while True:
        n = input("Enter a number (to quit): ")
        if n =="":
            break

您正在覆盖n,并且只有在n=="".

之后,您尝试将n(即"")解析为int,但正如预期的那样失败。

删除循环,它将起作用:

n = int(input("Enter a number: "))
于 2021-11-12T21:47:38.517 回答