python理解全局变量的好例子:山姆抽牌。

规则很简单,就是一副牌,两人各抽4张。

import random
print("Sam's Casino")
cards = ['1','2','3','4','5','6','7','8','9','10','J',
'Q','K','1','2','3','4','5','6','7','8','9','10','J',
'Q','K','1','2','3','4','5','6','7','8','9','10','J',
'Q','K','1','2','3','4','5','6','7','8','9','10','J',
'Q','K']
random.shuffle(cards)
print(cards)
hand1 = []
hand2 = []
count = 0

def deal(cards): 
    for card in cards:
        if count < 4:
            hand1.append(card)
            count += 1
            
        if count > 3 and count < 8:
            hand2.append(card)
            count += 1
           
deal(cards)
print('hand1',hand1)
print('hand2',hand2)
input('>')
 

UnboundLocalError: local variable 'count' referenced before assignment

很多人肯定很奇怪,大家都是全局变量,为什么hand1,hand2 没问题,count就有问题呢?原因很简单,hand1和hand2没有被引用,而是被赋值。

import random
print("Sam's Casino")
cards = ['1','2','3','4','5','6','7','8','9','10','J',
'Q','K','1','2','3','4','5','6','7','8','9','10','J',
'Q','K','1','2','3','4','5','6','7','8','9','10','J',
'Q','K','1','2','3','4','5','6','7','8','9','10','J',
'Q','K']
random.shuffle(cards)
print(cards)
hand1 = []
hand2 = []
count = 0

def deal(cards): 
    global count
    for card in cards:
        if count < 4:
            hand1.append(card)
            count += 1
            
        if count > 3 and count < 8:
            hand2.append(card)
            count += 1
           
deal(cards)
print('hand1',hand1)
print('hand2',hand2)
input('>')

输出

这才改写了count,否则for循环内部处理是局部变量,全局和其他函数都无关。但是光声明也不行,如果删掉count = 0 只保留global count, 那么

NameError: name 'count' is not defined

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞行codes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值