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.
the str variable has 1... (with dots)
at this point, you have to create a list and sum all your list members.
try this:
>>> nums_str = ",".join(["1"] * 1000) # or more
>>> nums_list = nums_str.split(",")
>>> result = 0
>>> for _ in nums_list: result += int(_)
>>> result
1000
or you can do this more compressed:
>>> result = 0
>>> for _ in [1] * 1000: result += _
>>> result
1000
just in 2 line (I meant compressed code)
note #1: never set variable names with built-in functions (example: hex, int, etc...)
note #2: take a look at this and this for _ (underscore) meanings.