Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convert String to Variable in the loop

Tags:

python

I would like to do something like this:

x = 0
y = 3

TEST0 = 10 
TEST1 = 20 
TEST2 = 30

while x < y:
    result = exec('TEST{}'.format(x))
    print(result)
    x += 1

And have the output:

10
20
30

Somehow convert TEST{variable} to the actual variable, or what is the way to do it?

Currently, I have result as:

None
None
None
like image 413
Oksana Krasiuk Avatar asked Nov 25 '25 05:11

Oksana Krasiuk


1 Answers

Welcome to Python! What you need is a list:

x = 0
y = 3

TEST = [10, 20, 30]

while x < y:
    result = TEST[x]
    print(result)
    x += 1

A list is created by putting the values between []. You access a particular element in the list by writing the name of the variable, followed by the index enclosed in []. Read more about lists here in the official tutorial.

Instead of the while loop with explicit indexing, it's nicer to use a for loop instead:

TEST = [10, 20, 30]

for element in TEST:
    result = element
    print(result)
like image 90
Thomas Avatar answered Nov 27 '25 17:11

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!