如果此变量是全局变量,为什么没有定义?

时间:2019-05-19 15:07:39

标签: python

我创建了一个列表,然后尝试将其追加到另一个列表,但是即使它是全局列表,仍然没有定义。

我在尝试将字符串追加到另一个列表时遇到了同样的问题,并且发生了相同的错误,因此我尝试将字符串设置为列表。

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)

现在我需要将击中附加到pHand(玩家的手)

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

2 个答案:

答案 0 :(得分:2)

global hit

这不会声明一个全局变量。它不会创建不存在的变量。它只是说“如果您在此范围内看到此名称,则假定它是全局名称”。要“声明”全局变量,您需要为其赋予一个值。

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

唯一需要global声明的时间是是否要分配给函数内部的全局变量,否则名称将被解释为局部变量。有关全局变量的更多信息,请参见this question

答案 1 :(得分:0)

OP的帖子中对global操作存在误解。函数内部的global告诉python在该范围内使用该全局变量名称。它本身不会使变量成为全局变量。

# 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"