Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating global variables from try block

I would like to update the global variable status after the try block runs successful. Is there a way to do so. The code below seem not work as intended.

status = "unsuccessful"

def test_func(a, b):
    global status
    try:
        return a + b
        status = "success"
    except TypeError:
        print("Wrong")


print(test_func(20, 1))
print(status)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The issue you are facing here is because status = "success" will never be reached. If your code enters the try block it’ll return a+b and exit the block. Putting the status = "success" line above the return line will fix your issue.

    try:
        status = "success"
        return a + b
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading