我应该如何去打印这个? (二十一点)

问题描述:

import random 

cards_names = {1: "Ace", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 
       9: "9", 10: "10", 11: "Jack", 12: "Queen", 13: "King"} 

def dealing(): 
    return random.randint(1, 13) 

def value_of_hand(cards): 
    value = 0 
    for card in cards: 
     if 1 < card <= 10: 
      value += card 
     elif card > 10: 
      value += 10 

    if 1 in cards and value + 11 <= 21: 
      return value + 11 
    elif 1 in cards: 
      return value + 1 
    else: 
      return value 

def your_hand(name , cards): 
    faces = [cards_names[card] for card in cards] 
    value = value_of_hand(cards) 

    if value == 21: 
     print ("Wow, you got Blackjack!") 
    else: 
     print ("") 

    print ("%s's hand: %s, %s : %s %s") % (name, faces[0], faces[1], value) 

for name in ("Dealer", "Player"): 
    cards = (dealing(), dealing()) 
    your_hand(name, cards) 
+2

我给你一个你很可能想得到的答案,但为了将来的参考,我建议你阅读[如何问](http://stackoverflow.com/help/how-to-ask)。简而言之:准确地说明您遇到的错误,您遇到问题的部分代码以及代码所需的行为。欢迎来到Stackoverflow! –

我在此假设您正在使用Python 3.x和收到此错误:

TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'

你必须%,此前移动的部分版画括号内,以避免错误。另外,您的印刷品中有太多的%s。卸下,然后将其打印罚款:

print ("%s's hand: %s, %s : %s" % (name, faces[0], faces[1], value)) 

Dealer's hand: Ace, 8 : 19

Player's hand: 9, 7 : 16

正如你所看到的,%s数量:■应该等于你提供给它的参数。如果没有在Python 3中删除多余%S将打印以下错误:

TypeError: not enough arguments for format string

此外,在Python 3,你可以使用新的字符串格式化语法:

print ("{}'s hand: {}, {} : {}".format(name, faces[0], faces[1], value)) 

有时比更灵活用旧的方式插入字符串用%s,肯定有用的功能就知道了。