从python中的列表中选择一张随机卡

时间:2015-06-16 01:31:17

标签: python random

所以我需要做一个"游戏"用户询问是否要选择卡的情况,如果是,则返回随机卡。像这样的东西:

>>>selectCard()
Would you like to draw a random card? (yes/no)
The card you got is: 8 of hearts
Would you like to draw a random card? (yes/no)
>>>yes
The card you got is: Ace of diamonds
Would you like to draw a random card? (yes/no)
>>>no
到目前为止,我有这个,但我被困住了,不知道如何完成它

def selectCards():
cardranks = ['Ace',1,2,3,4,5,6,7,8,9,'Jack','Queen','King','Ace',1,2,3,4,5,6,7,8,9,'Jack','Queen','King','Ace',1,2,3,4,5,6,7,8,9,'Jack','Queen','King','Ace',1,2,3,4,5,6,7,8,9,'Jack','Queen','King']
cardsuits = ['of Clubs','of Clubs','of Clubs','of Clubs','of Clubs','of Clubs','of Clubs','of Clubs','of Clubs','of Clubs','of Clubs','of Clubs','of Clubs','of Diamonds','of Diamonds','of Diamonds','of Diamonds','of Diamonds','of Diamonds','of Diamonds','of Diamonds','of Diamonds','of Diamonds','of Diamonds','of Diamonds','of Diamonds','of Hearts','of Hearts','of Hearts','of Hearts','of Hearts','of Hearts','of Hearts','of Hearts','of Hearts','of Hearts','of Hearts','of Hearts','of Hearts','of Spades','of Spades','of Spades','of Spades','of Spades','of Spades','of Spades','of Spades','of Spades','of Spades','of Spades','of Spades','of Spades']
shuffle(cardranks)
shuffle(cardsuits)
for a,b in zip(cardranks,cardsuits):
    response = (input ('Would you like to draw a random card? (yes/no)'))
    if response == yes:
        return (a,b)

当我运行这个程序时,它说肯定没有定义,因此我不知道如何继续。

谢谢

3 个答案:

答案 0 :(得分:1)

输入传递一个字符串,因此您必须检查是否收到字符串'yes'而不仅仅是。是的不是价值或变量。

最佳实践的细节:我喜欢你给出好的变量名,但是响应用s拼写;)

答案 1 :(得分:0)

问题在于,当您检查响应(拼写错误的响应错误)是否等于是时,您将它与未定义的变量“是”进行比较,您需要做的是:

#The '.upper()' bit changes the response string to uppercase.
if response.upper() == 'YES': #Yes must be in quotes to be a string comparison.
    print('Its Working!') #Prints out Its Working! to the Python IDE.

答案 2 :(得分:0)

您需要将yes括在引号中:'yes' - 因为现在您正在告诉Python解释器将其与变量中包含的值进行比较 yes而不是文字字符串 'yes'。通过将response转换为小写来使检查不区分大小写也是一个好主意:

response = input ('Would you like to draw a random card? (yes/no)')
if response.lower() == 'yes':
    # Return the card

然后您的代码还有一些其他问题:

  1. 如果用户不想绘制卡片,for循环将继续运行。这意味着您必须在循环结束前输入 no 52次,并且函数返回时不会绘制卡片。
  2. 在拖曳zip(cardranks,cardsuits)cardranks之后,
  3. cardsuits不会给你一个有效的,正常的套牌 - 你最终可能会得到一个有4个黑桃王牌而没有任何其他王牌的套牌适合例如。
  4. 更好的解决方案是:

    # All possible ranks
    cardranks = ['Ace','1','2','3','4','5','6','7','8','9','Jack','Queen','King']
    # All possible suits
    cardsuits = ['of Clubs','of Diamonds','of Hearts','of Spades']
    
    # The complete deck
    deck = list(itertools.product(cardranks, cardsuits))
    
    # Shuffle the deck
    random.shuffle(deck)
    
    # Draw a random card from the deck (the deck doesn't need to be shuffled before)
    rank, suit = random.choice(deck)
    
相关问题