I'm trying to develop a program that sums a thousand times '1' in a variable with Python.
str='1,1,1,1,1,1... to 1000
list=str.split(",")
Sum=0
for i in list:
Sum+=int(i)
it gives me an error, I'm wondering why?
I'm trying to develop a program that sums a thousand times '1' in a variable with Python.
str='1,1,1,1,1,1... to 1000
list=str.split(",")
Sum=0
for i in list:
Sum+=int(i)
it gives me an error, I'm wondering why?
Your construction is not correct. What do you think it's supposed to do?
str='1,1,1,1,1,1... to 1000'
Because your error is when Sum+=int(i)
and i
equals '1...'
which is obviously an invalid literal for int().
Try instead:
s = ','.join(['1']*1000)
Sum = sum(int(i) for i in s.split(','))
print(Sum)
# Output:
1000
Don't use builtin names as variable names. NEVER
You get the error invalid literal for int() with base 10: '1...'
because you have passed the str varibale exactly the way it is on the question ( i.e str='1,1,1,1,1,1... to 1000
). You cannot expect python to to understand english right ? :)
Try this instead:
ones = ','.join(['1']*1000)
one_list = ones.split(",")
Sum=0
for i in list:
Sum+=int(i)
Note: I changed the variable names because using python built-in names as variable names is not recommended as the names will not work as they are supposed to.