【发布时间】:2015-08-19 11:49:55
【问题描述】:
在下面的代码中,我运行了一个二十一点游戏,我想用一个函数计算任何一手牌(用户或庄家的)。当我运行代码时没有出现错误,但是当我调用该函数时,不会打印总手牌值。它只是说“这为您提供了总计:”并且数字为空白。见以下代码:
user_name = input("Please enter your name:")
print ("Welcome to the table {}. Let's deal!".format(user_name))
import random
suits = ["Heart", "Diamond", "Spade", "Club"]
ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
deck = [(suit, rank) for rank in ranks for suit in suits]
random.shuffle(deck,random.random)
user_hand = []
dealer_hand = []
user_hand.append(deck.pop())
dealer_hand.append(deck.pop())
user_hand.append(deck.pop())
dealer_hand.append(deck.pop())
def handtotal (hand):
total = 0
for rank in hand:
if rank == "J" or "Q" or "K":
total += 10
elif rank == 'A' and total < 11:
total += 11
elif rank == 'A' and total >= 11:
total += 1
elif rank == '2':
total += 2
elif rank == '3':
total += 3
elif rank == '4':
total += 4
elif rank == '5':
total += 5
elif rank == '6':
total += 6
elif rank == '7':
total += 7
elif rank == '8':
total += 8
elif rank == '9':
total += 9
return total
print (total)
print ("Your current hand is {}".format(user_hand))
print ("This provides you with a total of:")
handtotal(user_hand)
【问题讨论】:
-
请注意,
if rank == "J" or "Q" or "K":不会按照您的想法行事,请参阅 this question。
标签: python function variables printing cumulative-sum