[英]Why is this variable not defined if it is a global variable?
我创建了一个列表,然后尝试将其追加到另一个列表,但是即使它是全局列表,也仍然没有定义。
我在尝试将字符串追加到另一个列表时遇到了同样的问题,并且发生了相同的错误,因此我尝试将字符串设置为列表。
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()
global hit
这不声明一个变量是全球性的。 它不会创建不存在的变量。 它只是说“如果您在此范围内看到此名称,则假定它是全局名称”。 要“声明”全局变量,您需要为其赋予一个值。
# At the top-level
hit = "Whatever"
# Or in a function
global hit
hit = "Whatever"
唯一需要global
声明的情况是,如果要分配给函数内部的全局变量,否则名称可以解释为局部变量。 有关全局变量的更多信息,请参见此问题 。
OP的职位对global
运作存在误解。 在global
的一个函数里告诉蟒使用该范围内的全局变量名。 它本身不会使变量成为全局变量。
# 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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.