0

I want to define numbers with "indices", and then refer to them using a running index, for example

a1=4
a2=3
a3=17
sum=0
for k in range(1,4):
    sum+=ak
print(sum)

This doesn't work, apparently I need to express ak in another way. How can I do that? Thank you in advance :)

J_J
  • 1
  • Do not use `sum` as a variable as you are overwriting the builtin sum function. Also, what are your trying to accomplish with `ak`? if you just want to sum then just do `sum([a1, a2, a3])` But as stated previously you overwrote the sum function so you will get an error `TypeError: 'int' object is not callable` – It_is_Chris Nov 04 '21 at 16:32
  • Use `a = 4, 3, 17` and refer value by index or simply iterate over values. – Olvin Roght Nov 04 '21 at 16:32
  • Put your numbers in a sequence (list, tuple or whatever), then you can loop on them: `a=[4,3,17]` and then `for k in range(len(a)): mysum += a[k]`, or, better, `for k in a: mysum += k` – gimix Nov 04 '21 at 16:35

2 Answers2

0

If you really want this approach then use exec:

exec(f"sum+=a{k}")

Note: I don't recommend using exec.

Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
0

IIUC what you want to do, you should rather use a container:

a list
a=[4,3,17]
my_sum=0
for k in range(3):
    my_sum += a[k]
print(my_sum)
a dictionary
a={'a1':4, 'a2':3, 'a3': 17}
my_sum=0
for k in range(1,4):
    my_sum += a[f'a{k}']
print(my_sum)

That said, this is much easier:

a=[4,3,17]
sum(a[0:3])

output: 24

mozway
  • 194,879
  • 13
  • 39
  • 75