How to Print Exec

How to print diff{k} ? It give me error. “K” is variable in digit.

exec(f’diff{k} = good{k}')
print(diff{k})

or

for k in range(5):
print(diff{k})

Not clear - what you want ?
It could be that there are two different outputs of exec ?
The output you get in terminal and
the output you would get in an editor ?

for k in range(5):
print(diff{k})

Can give an output of variable name of
diff0
diff1
diff2
diff3
diff4
diff5

Above code not working

Hello Steven, and welcome!

As a beginner, you should not use exec. Even experts hardly ever use
exec. First you should learn how to use Python well, before trying to
use exec.

If “k” is a variable, you can print k like this:

print(k)

I don’t know what you mean by “diff{k}”, that is a SyntaxError.

It might help if you show us an example of your variables, and what
result you are trying to get. That would be better than showing us two
examples of code that don’t work.

Try using a list, not “diff1”, “diff2” etc variables.

Remember that lists start at 0, not 1.

diff = ['cat', 'dog', 'fox', 'bat', 'eel']
for k in range(5):
    print(diff[k])

Ah. You want a format string:

print(f"diff{k}")

The leading f" indicates that this is format string. The “diff” part
it leiteral text, uncanged, and the {f} indicates that the value of
k is to be inserted.

Cheers,
Cameron Simpson cs@cskk.id.au

Hi Cameron,

What Steven (the other Steven, not me) thinks he wants and what
he actually needs are probably not the same. He seems to have a bunch of
dynamically named variables diff1, diff2, diff3, diff4, diff5… when he
should be using a list.

Ah, I misread his list of variables whose values he wanted, as his
actual desired output. You’re right, he wants a list.

Cheers,
Cameron Simpson cs@cskk.id.au

Almost there.
diff1, diff2, diff3 etc are variables that contain some value inside. i need to print the value inside the variables. It currently print the variable name diff1, diff2, diff3 etc instead of the value inside.

You really, really don’t want to do it this way. You might think that
you do now, but in a few months, when you have learned how to program in
Python, you will realise that this is a bad idea.

# This is the WRONG way
diff1 = 'cat'
diff2 = 'dog'
diff3 = 'bee'
for i in range(1, 4):
    print(locals()[f'diff{i}'])


# This is the right way.
diff = ['cat', 'dog', 'bee']
for i in range(3):
    print(diff[i])

Thank U, I have learned.