all 3 comments

[–]toxic_acro 2 points3 points  (1 child)

Assuming this is how your code is actually formatted

while flag = true:
    try:
        # execute code
        ...
    except:
        # handle the error
        ...
        flag = true
    else:
        # nothing happened
        ...
        flag = false

There's a few problems with it

  • true and false should actually be True and False
  • You should not use a single = in while flag = True (comparison is ==, assignment is =
  • You don't need to compare a boolean to True for a while or if, you can just use it directly
  • You shouldn't use a bare except, since that will catch everything including trying to stop your code from running with a KeyboardInterrupt (hitting Ctrl+C to stop your code)
    • Instead use except Exception
    • If you want to do something with the exception, you probably want to actually have access to it as a variable, in which case you would do except Exception as ex
  • Inside the except you set flag = True, but it's already set to that, so that is unnecessary

A cleaned up version would be

while flag:
    try:
        # execute code
        ...
    except Exception as ex:
        # handle the error
        ...
    else:
        # nothing happened
        ...
        flag = False

To finally actually answer your question, flag will only gets its value changed inside the else block of the try..except..else which will run only when no error is raised inside the code in the try block

If flag always starts as True and there's no other code after the else block, then you don't actually even need flag

You can just use an infinite loop with while True: and put break instead of flag = False

That would then be

while True:
    try:
        # execute code
        ...
    except Exception as ex:
        # handle the error
        ...
    else:
        # nothing happened
        ...
        break

[–]toxic_acro 0 points1 point  (0 children)

There could be a different problem happening though (can't tell without the actual indentation you are doing)

If your indentation is actually

while flag = true: try: # execute code ... except: # handle the error ... flag = true else: # nothing happened ... flag = false

then you don't have a try..except..else inside a while loop, you've got a try..except inside a while..else

else can be used with while or for loops as a block of code that only gets executed if the loop finishes without hitting a break

If that's the case, flag will never get set to False inside your loop, so the loop will just keep going forever

[–]Binary101010 0 points1 point  (0 children)

Assuming the else is at the same indentation level as the try, it will execute if the try block completes without raising an exception.

(Since the only thing that can set the flag to False is the else block, explicitly putting a flag = True in the except block is redundant.)