If you really want to do this, you would have to access those variables by names that are stored in another variable. Some people call it "dynamic variable names". One option, once again if you really want to do it, is to use globals()
:
for x in ['A', 'B', 'C']:
print(f'The value of the model {x} is:', globals()[x + '_PR'])
# The value of the model A is: 3
# The value of the model B is: 4
# The value of the model C is: 6
But it is not recommended: see How do I create variable variables?.
So one of better options might be to use an iterable data type, such as dict
:
models = {'A': 3, 'B': 4, 'C': 6}
for x in ['A', 'B', 'C']:
print(f'The value of the model {x} is: {models[x]}')
It can be further simplified using items
, although I am not a huge fan of this, if I want to preserve the order.
models = {'A': 3, 'B': 4, 'C': 6}
for k, v in models.items():
print(f'The value of the model {k} is: {v}')
(A dict
does preserve the order, but in my mind, I treat dict
as not being ordered conceptually).