How to Print Exec

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

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


for k in range(5):

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

Can give an output of variable name of

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:


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

Ah. You want a format string:


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.

Cameron Simpson

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.

Cameron Simpson

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

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

Thank U, I have learned.