在 Python 中,为什么我的随机卡生成器的输出打印"None"?



我正在制作一个扑克牌生成器。在其中,一副由 52 张牌组成的牌被洗牌,并根据用户的选择随机抽取数量的牌。似乎一切都很好,除了最重要的部分。在应该列出卡片的地方,打印的只是"无":

亲眼看看

这是我的代码。有人有什么想法吗?这简直让我发疯了!

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 Dealern')
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!')

您忘记在 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!

最新更新