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.

2
  • 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. Commented Jun 14, 2022 at 2:57
  • 1
    Does this answer your question? How do I create variable variables? Commented Jul 5, 2022 at 2:08

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.