Home > Back-end >  python call variable in for loop
python call variable in for loop

Time:06-14

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.

CodePudding user response:

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

CodePudding user response:

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
  • Related