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

How to use correctly global variables inside if/elif conditions (python)?

I have this code:
When i change the variables value it gives me NameError: name ‘y’ is not defined
How can I solve?

def a():

    if 5 == 5:
    
       global x
       x = 39
       return True

    elif 6 == 6:

       global y 
       y = 3 
       return True




def b():


    if x == 3:
        print("ok")

    elif y == 3:
        print("no")
    
a()
b()

>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

you are returning Ture in the first if statement and the declaration of y is within an elif statement, these two things prevent y from ever being defined

def a():
    check_1 = False
    check_2 = False

    if 5 == 5:
    
       global x
       x = 39
       check_1 = True

    if 6 == 6:
       global y
       y = 3
       check_2 = True

    return (check_1 and check_2)


def b():

    if x == 3:
        print("ok")

    elif y == 3:
        print("no")
    
a()
b()

will output

no
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