0

Recently I learn about PHP and in PHP I can do this

$var_1 = "";
$var_2 = "something";
$var_3 = "";
for($i = 1; $i <= 3; $i++){
  if(${"var_". $i} = ""){
    // do something
  }else{
    // do something
  }
}

And I want to know can I implement this to the python ? Thank you.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • The way you do multiple variables distinguished by a changing number is as a single list or dictionary, with the changing number as an index. – jasonharper Jun 14 '22 at 02:57
  • 1
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Karl Knechtel Jul 05 '22 at 02:08

2 Answers2

1

Yes, but yuck, it is a horrible practice. Use a list and iterate directly instead of indexes. You can access an individual variable via var[index] if needed.

items = ['', 'something', '']
for item in items:
    if item == '':
        print('do something1')
    else:
        print('do something2')

Output:

do something1
do something2
do something1
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0

You can use the globals() function in python to access variables by their names as a string reference.

Here is an example of what you want to do:

var_1 = ""
var_2 = "something"
var_3 = ""
for i in range(1, 4):
    if globals()[f"var_{i}"] == "":
        # do something
    else:
        # do something
Blackgaurd
  • 608
  • 6
  • 15