0

I'm looking for print some variables more quickly. The code that i'm using is:

A_PR=3
B_PR=4
C_PR=6
print('the value of the model A is:', A)
print('the value of the model B is:', B)
print('the value of the model C is:', C)

I was thinking in a loop with a the for, but I couldn't make it work.

  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 26 '21 at 22:47

4 Answers4

1

You can use string formatting like this:

A_PR=3
B_PR=4
C_PR=6

print('Model A: {} \nModel B: {}\n Model C: {}'.format(A_PR, B_PR, C_PR))

Or you could embed those values into a array and loop over that array. Using ASCI values you can print A - Z model results

A_PR=3
B_PR=4
C_PR=6
model_results = [A_PR, B_PR, C_PR]

for idx, result in enumerate(model_results):
    print('Model {}: {}'.format(chr(idx + 65), result))

Output:

Model A: 3
Model B: 4
Model C: 6

nkacolz
  • 214
  • 1
  • 8
1
    model_dict = {'A':3, 'B':4, 'C':6,}
    for k,v in model_dict.items():
        print(f"the value of model {k} is: {v}")

Here's a simple solution I whipped up using python f strings and a dictionary

0

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).

j1-lee
  • 13,764
  • 3
  • 14
  • 26
0

Something like this should work as a small dictionary with a for loop. Simply unpack keys and values.

PR = {
    "A_PR": 3, "B_PR" :4 , "C_PR":6,
}

for k,v in PR.items():
    print(f'the value of the model {k} is: {v}')