简体   繁体   中英

Why is this variable not defined if it is a global variable?

I create a list and try to append it to another list, but even though it is a global list it still is not defined.

I had the same issue trying to apppend a string to another list, and that had the same error so I tried to make the string a list.

sees if the player hits

def hit_or_stand():
    global hit **<-- notice hit is a global variable**
    if hitStand == ("hit"):
            player_hand()
            card = deck()
            hit = []
            hit.append(card)

now I need to append hit to pHand (player's hand)

def player_hand():
    global pHand
    deck()

    pHand = []

    pHand.append(card)
    deck()
    pHand.append(card)
    pHand.append(hit) **<--- "NameError: name 'hit' is not defined"**
    pHand = (" and ").join(pHand)

    return (pHand)

hit_or_stand()
player_hand()
global hit

This does not declare a variable which is global. It does not create a variable which does not exist. It simply says "if you see this name in this scope, assume it's global". To "declare" a global variable, you need to give it a value.

# At the top-level
hit = "Whatever"
# Or in a function
global hit
hit = "Whatever"

The only time you need a global declaration is if you want to assign to a global variable inside a function, as the name could be interpreted as local otherwise. For more on globals, see this question .

There is a misunderstanding of the global operation in OP's post. The global inside a function tells python to use that global variable name within that scope. It doesn't make a variable into a global variable by itself.

# this is already a global variable because it's on the top level
g = ''

# in this function, the global variable g is used
def example1():
    global g
    g = 'this is a global variable'

# in this function, a local variable g is used within the function scope
def example2():
    g = 'this is a local variable'

# confirm the logic
example1()
print( g ) # prints "this is a global variable"
example2()
print( g ) # still prints "this is a global variable"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM