0

I wanted to code a program thats makes variables with loops like this:

for k in range(5):
    exec(f'test_{k} = k')

But the problem is that I want to do the same thing but reading the values from the variables:

for k in range(5):
    print('test_'+ k )

I know that it is not gonna work because:

  1. it is int to str (it is giving this error)
  2. it is not gonna print the value of the variable (because he dosent know that it is a variable)

Can someone help me?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

2 Answers2

0

For your first question, you already solved it in your first example (f'test_{k} = k'), so you would do the same in your second example.

for k in range(5):
    exec(f'print(test_{k})')

Or you can read the value first with exect(f'test_{k}') or eval(f'test_{k}') then do whatever you want with it.

Or even using globals() or locals().

Haytam
  • 4,643
  • 2
  • 20
  • 43
0

First of all the print() you are using literally prints the strings, and it should cast error because strings and ints cannot be concatenated:

for k in range(5):
    print(globals()[f'test_{k}'])

Second, eval() can be dangerous if input is malicious, so to avoid it use globals():

for k in range(5):
    globals()[f'test_{k}'] = k

And finally, Best way is to use dictionary for this:

varDic = {f'test_{k}':k for k in range(5)}

And retrieve like:

varDic['test_3']

inside a loop or other.

Wasif
  • 14,755
  • 3
  • 14
  • 34