0

I want to make a1=0, a2=0,... aN=0. I thought using "for"

For example N=10

for i in range(0, 10):

   print('a%d'%i)

but it isn't not zeros(just print). So, I did 'a%d'%i=0. but It didn't work

How can I make that?

sme
  • 4,023
  • 3
  • 28
  • 42
JIN BB
  • 3
  • 1

3 Answers3

1

You can use a dictionary for that.

var_name = 'a'

for i in range(0, 10):   
    key = var_name + str(i) # an
    new_values[key] = 0 # assign 0 to the new name

For accessing them individually,

new_values['a1']
>>> 0

or you can access them all together like this,

for k,v in new_values.items():
    print(k,'=',v)

outputs:

a0 = 0
a1 = 0
a2 = 0
a3 = 0
a4 = 0
a5 = 0
a6 = 0
a7 = 0
a8 = 0
a9 = 0
Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34
1

Simple solution, using const value x=0, and counter i:

x = 0
for i in range(0,10):
    print(f"a{i} = {x}")

output:

a0 = 0
a1 = 0
a2 = 0
a3 = 0
a4 = 0
a5 = 0
a6 = 0
a7 = 0
a8 = 0
a9 = 0
dejanmarich
  • 1,235
  • 10
  • 26
1

For printing use .format() (or f-strings on python 3.6+ :

for i in range(0, 10):
    print('a{} = {}'.format(i,i))  # the 1st i is put into the 1. {}, the 2nd i is put ...

If you want to calculate with those as names, store them into a dictionary and use the values to calculate with them:

d = {}
for i in range(0, 10):
    d["a{}".format(i)] = i # the nth i is put instead nth {}

print("sum a4 to a7:  {} + {} + {} + {} = {}".format(   # use the values stored in dict to 
    d["a4"], ["a5"], ["a6"], ["a7"],                    # calculate and print the single 
    d["a4"]+d["a5"]+d["a6"]+d["a7"]))                   # values where needed 

Output:

# for loop 
a0 = 0
a1 = 1
a2 = 2
a3 = 3
a4 = 4
a5 = 5
a6 = 6
a7 = 7
a8 = 8
a9 = 9

# calculation
sum a4 to a7:  4 + ['a5'] + ['a6'] + ['a7'] = 22
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69