这是我编写的一些Python代码,用于生成一个随机的扑克手,只是为了它/它的挑战,但当我尝试运行它时,我得到上面的错误“如果卡在手”。发生了什么,为什么会发生这种情况,特别是因为那条线没有迭代?
import random
def pokerHand():
hand = ["This is your hand:"]
x = 0
while x < 5:
cardNum = random.randrange(13) + 1
if cardNum == 1:
cardNum = "Ace of "
elif cardNum == 11:
cardNum = "Jack of "
elif cardNum == 13:
cardNum = "King of "
elif cardNum == 12:
cardNum = "Queen of "
else:
cardNum = str(cardNum) + " of "
cardSuit = random.randrange(4)
if cardSuit == 0:
cardSuit = "Clubs"
elif cardSuit == 1:
cardSuit = "Diamonds"
elif cardSuit == 3:
cardSuit = "Hearts"
elif cardSuit == 2:
cardSuit = "Spades"
card = cardNum + cardSuit
if card in hand: #<the line of error
pass
else:
hand = hand.append(card)
x = x + 1
for xx in hand:
print xx
答案 0 :(得分:7)
hand = hand.append(card)
append
不会返回任何内容。将其更改为:
hand.append(card)
答案 1 :(得分:3)
列表的append()
方法不会返回列表,它会在适当的位置修改它。因此,在添加第一张卡片(带hand = hand.append(card)
)后,hand设置为append()
的返回值,即None
(没有显式{{1}的方法的返回值}})。您应该将其更改为return
答案 2 :(得分:0)
list.append不会返回附加值的列表,而是将值附加到列表中并返回None。这样做:
else:
hand.append(card)
...