code_0 = 0,
code_1 = 1,
code_2 = 2
for n in range(3):
print(code_n) # <<<<< This is problem
result = 0
1
2
I want to put a repeating number into a variable. how I solve?
CodePudding user response:
To answer your question, You can use globals()
which returns a dictionary of the variables defined in the environment, and you can call get()
on this dictionary object to get the value of a variable by its corresponding name.
code_0 = 0
code_1 = 1
code_2 = 2
for n in range(3):
print(globals().get(f"code_{n}"))
#output:
0
1
2
But instead of accessing globals()
directly, you can define codes
list with the list of values and get the values in the list by index:
codes = [1,2,3]
for i in range(len(codes)):
print(codes[i])
#output:
1
2
3
CodePudding user response:
assign result as a list and append these code into it, then print will show all codes.
result = []
for n in range(3):
result.append(code_n)
print