0

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 1
    Note: `list` is a builtin type just like `dict` or `str` in python, so please use other names for your vars since you will get into trouble later if you replace the builtins. You also use the var `Sum` that do not conflict with anything, but the lowercase `sum` is a builtin so there could be some confusion here as well. So think about your naming and keep up the fun :) – UlfR Oct 21 '21 at 06:55
  • Do you want to do the addition with `'1'` or `1`? The first is a string and the second is a number. I suspect you want the numbers, but according to the description in your question you want the string. – Matthias Oct 21 '21 at 07:09
  • You have to use `','.join(['1']*1000)` intead of `'1,1,1,1,1,1... to 1000'` – Shwetha Oct 21 '21 at 07:48
  • Can you please [edit] the question to provide a [mre]? It is not really clear what output you expect, nor what exactly you are working with. The code taken at face value fails with a ``SyntaxError``, and applying obvious fixes leads to a slightly different failure than in the title. It would likely also be useful to clarify why you think *any* variation of "1,1,1... to 1000" would be sensible for Python, so that this misconception can be cleared up. – MisterMiyagi Oct 21 '21 at 10:48

2 Answers2

0

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

Corralien
  • 109,409
  • 8
  • 28
  • 52
0

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.

Shwetha
  • 106
  • 8