Home > Back-end >  Move to else statement based on variable update outside if-else statement
Move to else statement based on variable update outside if-else statement

Time:08-17

Folks, this may be small query but i am stuck in here, anyone could help me understand my requirement will be appreciated.

check = True
if check:
    for i in dict:
        if i in another_dict:
            do something
        else:
            check = False

else:
    status = True

if status:
    do something

else:

Initially I am assigned True(bool) value to a variable outside IF-ELSE statement, I want to move to else statement if I update the same variable from inside IF statement.

(i.e ) in the above code, I want to continue with main else statement if the variable "check" = False

CodePudding user response:

Just use another if. If check was updated inside the first if, it will go into the second if:

check = True
status = False

if check:
    for i in dct:
        if i in another_dict:
            do_something()
        else:
            check = False

if not check:
    do_something()
    status = True

if status:
    do_something()

CodePudding user response:

To go to the outer else you will need to break out of the loop you are in.

for i in dict:

However, even if the loop finishes, "check" will not be checked again because it already has been once. To understand it better, we have already crossed the line:

if check

And we will not be coming back to it, since there is no loop.

Considering all this, the best solution is to add another check at the end of the code to see if check == false and do whatever you have to do.

check = True
if check:
    for i in dict:
        if i in another_dict:
            do something
        else:
            check = False

else:
    do something

if not check
    do something

CodePudding user response:

Use check as global variable.. .you change the value of a global variable inside a function, refer to the variable by using the global keyword:

x = "awesome"

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is "   x)
  • Related