gpt4 book ai didi

python - 将 for 循环放入函数中时出现问题 (Python3)

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:21 25 4
gpt4 key购买 nike

此帖已回复,喜欢的可以看看。

我一直在尝试用 python 3 编写纸牌游戏,并且一直在使用 for 循环将纸牌从牌组列表转移到手牌列表。我试图将其放入一个函数中,但命令提示符崩溃了。帮助?

from random import *
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']
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)
print(hand2)
input('>')

编辑:没有收到错误,它只是关闭。

最佳答案

UnboundLocalError: local variable 'count' referenced before assignment

count 放在函数 deal

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

这有效。

关于python - 将 for 循环放入函数中时出现问题 (Python3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50866754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com