在Python中,为什么我的随机卡生成器的输出显示'None'?

问题描述 投票:0回答:1

我正在制作纸牌生成器。在其中,一副52张纸牌被洗牌,并根据用户的选择随机抽取了几张纸牌。除了最重要的部分外,其他一切似乎都正常。列出卡片的位置,所有打印的内容均为“无”:

See for yourself

这是我的代码。谁有想法?这让我发疯了!

import random

class Card:
    ranks = {2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10', 11: 'Jack', 12: 'Queen', 13: 'King', 1: 'Ace'}
    suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades']

    def __init__(self):
        pass 

    def string_of_card(self, num):
        x = ""
        if 1 <= num <= 13:
            x = self.ranks[num] + ' of '+self.suits[0]
        elif 14 <= num <= 26:
            x = self.ranks[(num % 13) + 1] + ' of '+self.suits[1]
        elif 27 <= num <= 39:
            x = self.ranks[(num % 13) + 1] + ' of '+self.suits[2]
        elif 40 <= num <= 52:
            x = self.ranks[(num % 13) + 1] + ' of '+self.suits[3]
        return x

class Deck:
    numbers = list(range(1, 53))


    def __init__(self):
        print('Card Dealer\n')
        self.shuffle_deck()
        print('I have shuffled a deck of 52 cards.\n')

    def shuffle_deck(self):
        random.shuffle(self.numbers)

    def count_cards(self):
        return len(self.numbers)

    def deal_card(self):
        self.shuffle_deck()
        num = random.choice(self.numbers)
        self.numbers.remove(num)
        c = Card()
        x = c.string_of_card(num)
        return

d = Deck()

n = int(input('How many cards would you like?: '))

print('\nHere are your cards: ')

for i in range(1, n + 1):
    print(d.deal_card())

print('\nThere are', d.count_cards(), 'cards left in the deck.\n')
print('Good luck!')
python object random output self
1个回答
3
投票

您忘了在您的deal_card()方法中返回卡的字符串。

def deal_card(self):
        self.shuffle_deck()
        num = random.choice(self.numbers)
        self.numbers.remove(num)
        c = Card()
        x = c.string_of_card(num)
        # you need to return the string of cards that are dealt
        return x

这里是我运行整个程序时的示例输出:

Card Dealer

I have shuffled a deck of 52 cards.

How many cards would you like?: 10

Here are your cards: 
3 of Spades
6 of Diamonds
7 of Diamonds
2 of Hearts
7 of Clubs
King of Hearts
10 of Spades
4 of Diamonds
6 of Spades
King of Spades

There are 42 cards left in the deck.

Good luck!
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.