For example, If i had code similar to this:
x1 = 1
x2 = 2
x3 = 3
for i in range(3):
#How do i get "x" + i and print the variable's value?
print()
For example, If i had code similar to this:
x1 = 1
x2 = 2
x3 = 3
for i in range(3):
#How do i get "x" + i and print the variable's value?
print()
If you want to iterate through the numbered variables without the use of an array,
you can use locals()
:
x1 = 1
x2 = 2
x3 = 3
for i in range(1,4): # Note that it's range(1,4) if you want 1, 2, 3
print(locals()[f"x{i}"])
Output:
1
2
3
not a huge amount of information about what you're asking here, but I think the below solves the it
x1 = 1
x2 = 2
x3 = 3
lst = [x1,x2,x3]
for i in lst:
print(i)
output:
1
2
3
You can do it using eval
function:
x1, x2, x3 = 1, 2, 3
for i in range(1,4):
print(eval("x"+str(i)))
Output:
% python3 script.py
1
2
3