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

Time:11-23

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()

CodePudding user response:

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

CodePudding user response:

In your code, y is never defined:

One way to fix it is:

def a():
    if 5 == 5:
       global x
       x = 39

    if 6 == 6:
       global y 
       y = 3 

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

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