0

Can you help me getting the correct output. I want to call P2, by combining P and 2, for a value of 34?

I assigned P2 = 34 , but if I want to combine P and 2 in M and I call M, I only get P2 as a string not a variable. I get that it happens, but I don't know how to solve it.

i=2
P2 = 34
M = 'P%s'%(int(i))
print(M)
print(P2)

Output:

P2
34

Expected output:

34
34

I will try to further explain my problem.

I have 3 matrices all are 3 by 3. They are called P1, P2, P3

I want to call each element of each matrix therefor I tried

for p in range(3):
    for i in range(3):
        for j in range(3):
            M = 'P%s'%(int(p))
            print(M[i,j])

Is it still the same problem of not using dict?

Jella
  • 1
  • 1
  • You're looking for a dictionary. – AKX Sep 19 '22 at 14:05
  • Any time, in any language, you are thinking "Variable variable names" or any variation thereof, think instead "Dictionary". If in that language, dictionaries aren't available, then think "array". There is only one language I'm aware of that natively supports variable variable names, but it's such a huge anti-pattern even in that language, it wouldn't be a good idea to utilize the feature. – JNevill Sep 19 '22 at 14:08
  • This is **very** bad practice, but you can always look in `globals()`, which is a dictionary of every variable: `print(globals()[M])` – The Thonnu Sep 19 '22 at 14:12
  • @TheThonnu It's such a bad practice that it shouldn't be mentioned, because dicts are a thing and are meant _just for this_ . – AKX Sep 19 '22 at 14:19
  • @Jella **Please** don't use that. Use a dict. – AKX Sep 19 '22 at 14:21
  • @AKX - I agree, it's very bad practice and shouldn't be used, but technically doesn't `globals()` return a dictionary, so it's a similar sort of thing? – The Thonnu Sep 19 '22 at 14:26
  • I have put further elaboration of the question above – Jella Sep 19 '22 at 14:29
  • 1
    Just make P a list! P[0]. P[1], P[2], then use P[i].... – Max Sep 19 '22 at 14:35

0 Answers0