[Tutor] ValueError: invalid literal for int() with base 10: '' is outcome in line 89--statSet.addNumber(int(n))
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Nov 13 06:04:19 EST 2021
On 12/11/2021 21:40, matt wrote:
> My code is ( i did try to give (int(float(n))) but it didn’t work either):
Always paste the entire error message not just the summary line.
There is a lot of information contained in the error but we
can't see it if you don't paste the whole thing.
> #statistics calc
BTW You did notice that there is a statistics module in the
standard library that does all the things you are trying to
do here? You could study the code for that to see how they do it.
> from math import sqrt
> class StatSet:
>
> def __init__(self):
> self.data = 0
>
> def getData(self):
> return self.data
In Python we don't usually create setters/getters, there is no need.
> def addNumber(self,x):
>
> if isinstance(x,(int,float)):
> data = self.data
> data.append(x)
> self.data = data
This makes no sense.
self.data is a number, 0 by default.
You cannot append() to a number.
You would need to create self.data as a list in the __init__()
> def mean(self):
> nums = self.data
> #check (if) cond.
Your comments are just replicating the code, they don't add
anything of value and make the code more cluttered. Use
comments to explain *why* the code does things, not *what* the
code does.
> if len(nums)>0:
> return sum(nums)/len(nums)
> else:
> return 0
That might result in confusing or even erroneous results.
It would be better to raise an exception than pass back
a wrong answer!
> def median(self):
> nums = self.data
> nums.sort()
> length = len(nums)
> remainder = length%2
> med = 0
> 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 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(self):
> count = len(self.data)
> return count
> def min(self):
> nums = self.data
> nums.sort()
> minNum = nums[0]
> return minNum
> def max(self):
> nums = self.data
> nums.sort()
> maxNum = nums[-1]
> return maxNum
You realize there are builtin functions min() and max()
for getting the min and max of a sequence?
def main()
> statSet = StatSet()
> while True:
> n = input("Enter a number (to quit): ")
> if n =="":
> break
> statSet.addNumber(int(n))
Note that the addNumber() is outside the loop so you
only ever add one number.
The subject line would suggest this is probably where
the error occurs but without seeing the error trace
(and ideally the data entered!) its hard to be sure.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list