Home > Back-end >  How to use the variable outside the function in a if Statement
How to use the variable outside the function in a if Statement

Time:05-21

    Def func1():
        H = 1

    func1()
    If H == 1:
       Print("nice")

Error: h is not defined

#i need this problem solved for my textadventure(its my first python project btw)

CodePudding user response:

You can return the variable to use it outside of the function:

def func1():
    H = 1
    return H

H = func1()
If H == 1:
   print("nice")

CodePudding user response:

This has to do with scope. In the function are assigning 1 to the variable H, although, by doing this, you are shadowing any global variable H since functions have their own scope separate from global, other functions, classes, etc...

If this expected behavior then use the global keyword from within the function.

def func1():
    global H
    H = 1

But this ↑ is (in most cases) bad practice

Instead you should be returning the value:

def func1():
    return 1

H = func1()
if H == 1:
    print("nice")

CodePudding user response:

Variable that declare inside function are local vriable. which means you can't access outside the function

Declare H as global and you can access variable H anywhere in the code

def func1():
    global H
    H = 1

func1()
if H == 1:
   print("nice")
  • Related