初学者:Python值错误:int()无效文字

时间:2022-03-30 18:21:50

Im making a simple blackjack program in python, but im getting a "ValueError: invalid literal for int() with base 10: ..." In order to get the total value of the player hands, after creating the card object, i try to get the rank of the card: rank1 = Card.Card.getRank(card1)

我用python做了一个简单的blackjack程序,但是我得到了一个“ValueError: int()和基数10的无效文字:…”为了获得玩家手的总价值,在创建了card对象后,我尝试获得card的rank: rank1 = card.card。getrank (card1)

heres the classs method:

希烈、方法:

 def getRank(self):
      if self.__rank == ('J'):
          self.__rank = 10
          return self.__rank
      elif self.__rank == ('Q'):
          self.__rank = 10
          return self.__rank
      elif self.__rank ==  ('K'):
          self.__rank = 10
          return self.__rank
      elif self.__rank == ('A'):
          self.__rank = 11
          return self.__rank
      else:
          self.__rank = self.__rank
          return int(self.__rank)`

the only time it returns the ValueError: invalid literal for int() with base 10 is if the rank is a 'Q' or 'K', it returns 10 for the 'J' and 11 for 'A'. I'm not getting why it returns an error for the 'Q' or 'K' since the code is the same for 'J' and 'A'... any help would be appreciated... if it helps, before that i had

唯一返回ValueError的时间:以10为基数的int()的无效文字是如果rank是“Q”或“K”,它将返回10的“J”,11表示“a”。我不明白为什么它会为Q或K返回一个错误,因为代码对'J'和'A'是一样的…如有任何帮助,我们将不胜感激。如果有帮助的话,在我之前。

heres the whole class

这是全班同学

#Card class

#Class card holds ranks and suits of deck
#

TEN = 10
FOUR = 4

class Card():
     #Create rank list
     RANK= ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]*FOUR


     #Create list with rank names
     rankNames=[None, 'Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 
                'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']


     #Create suit list
     suitNames = ['CLUBS','DIAMONDS', 'HEARTS', 'SPADES']


     #Takes in rank, suit to create a deck of cards
     def __init__(self, rank, suit):
          self.__rank = rank
          self.__suit = suit


     #Returns the rank of card
     def getRank(self):
          if self.__rank == ('J'):
              print (repr(self.__rank))
              self.__rank = 10
              return self.__rank
          elif self.__rank == ('Q'):
              self.__rank = 10
              print (repr(self.__rank))
              return self.__rank
          elif self.__rank ==  ('K'):
              print (repr(self.__rank))
              self.__rank = 10
              return self.__rank
          elif self.__rank == ('A'):
              print (repr(self.__rank))
              self.__rank = 11
              return self.__rank
          else:
              self.rank = self.__rank
              print (repr(self.__rank))
              return int(self.__rank)   


     #Returns suit of card
     def getSuit(self):
          return self.__suit


     #Returns number of points the card is worth
     def BJVaue(self):
          if self.rank < 10:
               return self.rank
          else:
               return TEN


     def __str__(self):
          return "%s of %s" % ([self.__rank], [self.__suit])

Heres where i create the card objects

这是我创建卡片对象的地方。

#Create a player hand                
player = []    
#Draw two cards for player add append
player.append(drawCard())
player.append(drawCard())

#Display players cards
print ("You currently have:\n" , player)

#Get the rank of the card
card1 = player[0]
card2 = player[1]

#Update players card status
print (card1)
print (card2)

#Get the total of the hand
rank1 = Card.Card.getRank(card1)
rank2 = Card.Card.getRank(card2)

#Get the ranks of players cards
playerRank = [rank1 , rank2]

#Get total of players hand
totalPlayer = getTotal(playerRank)

#Display players total
print ("Your current total is: ", totalPlayer)

the getTotal function

getTotal函数

def getTotal(rank):
    #Create and set accumulator to 0
    total = 0

    #for each value in the rank
    for value in rank:
        #add to total
        total += value

    #Return total
    return total

hope this helps

希望这有助于

5 个解决方案

#1


3  

This line isn't right:

这条线是不对的:

  if self.__rank == ('J' or 'Q' or 'K'):

('J' or 'Q' or 'K') evaluates to 'J', so this line just checks whether self.__rank == 'J'.

('J'或'Q'或'K')计算为'J',所以这条线只检查self。__rank = =“J”。

You actually want:

你真正想要的:

  if self.__rank in ('J', 'Q', 'K'):

I think your first code example should work. Are you sure that you're actually running the new code? If you try to import the same module into a running Python instance it won't pick up the changes. Also, if you redefine a class, existing instances will still have the old method implementations.

我认为您的第一个代码示例应该有效。你确定你正在运行新代码吗?如果您试图将同一个模块导入到运行的Python实例中,那么它将不会接受更改。另外,如果重新定义一个类,现有的实例仍然会有旧的方法实现。

#2


1  

You've got fairly stinky code here - bad indentation, unnecessary brackets (are those strings or tuples?), nasty mix of functional and OO, static calls to non-static methods, etc.

这里有非常糟糕的代码——糟糕的缩进,不必要的括号(这些字符串或元组?),功能和OO的混合,静态调用非静态方法等等。

The initial problem, "ValueError: invalid literal for int() with base 10: ..." means you are passing int() a value which it doesn't know how to translate into an integer. The question, then, is: what is that value, and where is it coming from?

最初的问题是“ValueError: int()以10为基数的无效文字:…”表示您正在传递int()值,该值不知道如何将其转换为整数。问题是,这个值是什么,它从哪里来?

Try substituting

尝试着用

    VALUE = {
        '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10,
        'J':10, 'Q':10, 'K':10, 'A':11
    }
    def getValue(self):
        try:
            return Card.VALUE[self.__rank]
        except KeyError:
            print "%s is not a valid rank" % (self.__rank)

and see what you get. My guess would be that drawCard is generating rank values that Card.getValue doesn't know what to do with.

看看你能得到什么。我猜这张拉卡产生的是rank值。getValue不知道该如何处理。

Other problems with your code:

代码的其他问题:

TEN = 10
FOUR = 4

The whole point of using defined values is to provide semantic meaning and allow a single point of change; yet FOUR is no more contextually meaningful than 4, and I see no case in which changing the value of FOUR or TEN would make sense (indeed, if FOUR were ever to equal 3, it would be actively unhelpful in understanding your code). Try renaming them FACECARD_VALUE and NUMBER_OF_SUITS.

使用定义值的全部意义在于提供语义含义并允许单点更改;然而,4没有比4更具有上下文意义,而且我认为,改变4或10的值是没有意义的(事实上,如果4个值等于3,那么在理解代码时,它将会是非常无益的)。试着将它们重命名为FACECARD_VALUE和NUMBER_OF_SUITS。

You are using "rank" to mean multiple different things: the character denoting a card and the value of a card to your hand. This will also increase confusion; try using face for one and value for the other!

你使用“rank”来表示多种不同的东西:字符表示一张牌和一张牌在你手中的值。这也会增加混乱;试着用一张脸和另一个的价值!

You seem to be using drawCard() as a stand-alone function; how are you keeping track of what cards have already been dealt? Does it ever make sense to have, for example, two Ace of Spades cards dealt? I would suggest creating a Deck object which initializes 52 canonical cards, shuffles them, and then deck.getCard() returns a card from the list instead of creating it randomly.

您似乎在使用drawCard()作为独立函数;你如何记录已经处理过的牌?举个例子,有两张黑桃牌,这有意义吗?我建议创建一个Deck对象,它初始化了52个标准卡片,并将其洗牌,然后Deck . getcard()从列表中返回一张卡片,而不是随机地创建它。

See what you think of the following:

看看你是怎么想的:

import random

class Deck():
    def __init__(self):
        self.cards = [Card(f,s) for f in Card.FACE for s in Card.SUIT]
        self.shuffle()

    def shuffle(self):
        random.shuffle(self.cards)

    def getCard(self):
        return self.cards.pop()

class Card():
    # Class static data
    FACE = ('A',   '2',   '3',     '4',    '5',    '6',   '7',     '8',     '9',    '10',  'J',    'Q',     'K')
    NAME = ('Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King')
    RANK = (11,    2,     3,       4,      5,      6,     7,       8,       9,      10,    10,     10,      10)
    SUIT = ('Clubs','Diamonds', 'Hearts', 'Spades')

    def __init__(self, face, suit):
        ind = Card.FACE.index(face)
        self.__face = Card.FACE[ind]   # the long way around, but keeps it consistent
        self.__name = Card.NAME[ind]
        self.__rank = Card.RANK[ind]

        ind = Card.SUIT.index(suit)
        self.__suit = Card.SUIT[ind]

    def getFace(self):
        return self.__face

    def getName(self):
        return self.__name

    def getRank(self):
        return self.__rank

    def getSuit(self):
        return self.__suit

    def __str__(self):
        return "%s of %s" % (self.__name, self.__suit)

    def __repr__(self):
        return "%s%s" % (self.__face, self.__suit[:1])

class Player():
    def __init__(self):
        self.cards = []

    def drawCard(self, deck):
        self.cards.append(deck.getCard())

    def drawCards(self, deck, num=2):
        for i in range(num):
            self.drawCard(deck)

    def getRank(self):
        return sum( c.getRank() for c in self.cards )

    def __str__(self):
        cards = ', '.join(str(c) for c in self.cards)
        return  "%s: %d" % (cards, self.getRank())

    def __repr__(self):
        return ' '.join([repr(c) for c in self.cards])

class Game():
    def __init__(self):
        self.deck = Deck()
        self.player1 = Player()
        self.player2 = Player()

    def test(self):
        self.player1.drawCards(self.deck, 2)
        print "Player 1:", self.player1

        self.player2.drawCards(self.deck, 2)
        print "Player 2:", self.player2

def main():
    g = Game()
    g.test()

if __name__=="__main__":
    main()

#3


0  

rank1 = Card.Card.getRank(card1)

This looks like you're trying to call the getRank as a static method. getRank is expecting an instance of itself as the first parameter. This usually means you have a Card object, but the way you call it above, you don't have an object to pass it. I'ms urprised it even lets you call it like that. That should give you an incorrect number of arguments error.

这看起来像是你试图把getRank称为静态方法。getRank希望将自己的实例作为第一个参数。这通常意味着您有一个卡片对象,但是您在上面调用它的方式,您没有一个对象可以通过它。我甚至让你这样称呼它。这会给你一个错误的参数错误数。

Post more code, but it seems like you have serious fundamental problems with your design.

发布更多的代码,但似乎你的设计有严重的基本问题。

Update:

更新:

What's this?

这是什么?

RANK= ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]*FOUR

Why do you need a list of 4 duplicates of your ranks?

为什么你需要一份名单,你的排名是4个副本?

#4


0  

Here is another approach to make a deck of cards

这是另一种制作扑克牌的方法。

from itertools import product

card_values = (
    ("1", "1", 1),
    ("2", "2", 2),
    ("3", "3", 3),
    ("4", "4", 4),
    ("5", "5", 5),
    ("6", "6", 6),
    ("7", "7", 7),
    ("8", "8", 8),
    ("9", "9", 9),
    ("10" ,"10", 10),
    ("Jack", "J", 10),
    ("Queen", "Q", 10),
    ("King", "K", 10),
    ("Ace", "A", 11))

card_suits = ("Spades", "Clubs", "Hearts", "Diamonds")

class Card(object):
    def __init__(self, name, short_name, rank, suit):
        self.name = name
        self.short_name = short_name
        self.rank = rank
        self.suit = suit  

cards = []
for (name, short_name, rank), suit in product(card_values, card_suits):
    cards.append(Card(name, short_name, rank, suit))

#5


0  

You could reduce the amount and complexity of your code by using a Python dictionary. If you did this, your getRank() function could look something like the following:

您可以使用Python字典减少代码的数量和复杂性。如果您这样做了,您的getRank()函数可能看起来如下:

class Card(object):
    RANK = {"A":1, "2":2,  "3": 3, "4":4,  "5": 5, "6": 6, "7":7,
            "8":8, "9":9, "10":10, "J":10, "Q":10, "K":10}

    def __init__(self, draw): # just for example
        self.__rank = draw

    def getRank(self):
        self.__rank = Card.RANK[self.__rank]
        return self.__rank
    #  ...

print Card('A').getRank()
# 1
print Card('4').getRank()
# 4
print Card('J').getRank()
# 10
print Card('K').getRank()
# 10

#1


3  

This line isn't right:

这条线是不对的:

  if self.__rank == ('J' or 'Q' or 'K'):

('J' or 'Q' or 'K') evaluates to 'J', so this line just checks whether self.__rank == 'J'.

('J'或'Q'或'K')计算为'J',所以这条线只检查self。__rank = =“J”。

You actually want:

你真正想要的:

  if self.__rank in ('J', 'Q', 'K'):

I think your first code example should work. Are you sure that you're actually running the new code? If you try to import the same module into a running Python instance it won't pick up the changes. Also, if you redefine a class, existing instances will still have the old method implementations.

我认为您的第一个代码示例应该有效。你确定你正在运行新代码吗?如果您试图将同一个模块导入到运行的Python实例中,那么它将不会接受更改。另外,如果重新定义一个类,现有的实例仍然会有旧的方法实现。

#2


1  

You've got fairly stinky code here - bad indentation, unnecessary brackets (are those strings or tuples?), nasty mix of functional and OO, static calls to non-static methods, etc.

这里有非常糟糕的代码——糟糕的缩进,不必要的括号(这些字符串或元组?),功能和OO的混合,静态调用非静态方法等等。

The initial problem, "ValueError: invalid literal for int() with base 10: ..." means you are passing int() a value which it doesn't know how to translate into an integer. The question, then, is: what is that value, and where is it coming from?

最初的问题是“ValueError: int()以10为基数的无效文字:…”表示您正在传递int()值,该值不知道如何将其转换为整数。问题是,这个值是什么,它从哪里来?

Try substituting

尝试着用

    VALUE = {
        '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10,
        'J':10, 'Q':10, 'K':10, 'A':11
    }
    def getValue(self):
        try:
            return Card.VALUE[self.__rank]
        except KeyError:
            print "%s is not a valid rank" % (self.__rank)

and see what you get. My guess would be that drawCard is generating rank values that Card.getValue doesn't know what to do with.

看看你能得到什么。我猜这张拉卡产生的是rank值。getValue不知道该如何处理。

Other problems with your code:

代码的其他问题:

TEN = 10
FOUR = 4

The whole point of using defined values is to provide semantic meaning and allow a single point of change; yet FOUR is no more contextually meaningful than 4, and I see no case in which changing the value of FOUR or TEN would make sense (indeed, if FOUR were ever to equal 3, it would be actively unhelpful in understanding your code). Try renaming them FACECARD_VALUE and NUMBER_OF_SUITS.

使用定义值的全部意义在于提供语义含义并允许单点更改;然而,4没有比4更具有上下文意义,而且我认为,改变4或10的值是没有意义的(事实上,如果4个值等于3,那么在理解代码时,它将会是非常无益的)。试着将它们重命名为FACECARD_VALUE和NUMBER_OF_SUITS。

You are using "rank" to mean multiple different things: the character denoting a card and the value of a card to your hand. This will also increase confusion; try using face for one and value for the other!

你使用“rank”来表示多种不同的东西:字符表示一张牌和一张牌在你手中的值。这也会增加混乱;试着用一张脸和另一个的价值!

You seem to be using drawCard() as a stand-alone function; how are you keeping track of what cards have already been dealt? Does it ever make sense to have, for example, two Ace of Spades cards dealt? I would suggest creating a Deck object which initializes 52 canonical cards, shuffles them, and then deck.getCard() returns a card from the list instead of creating it randomly.

您似乎在使用drawCard()作为独立函数;你如何记录已经处理过的牌?举个例子,有两张黑桃牌,这有意义吗?我建议创建一个Deck对象,它初始化了52个标准卡片,并将其洗牌,然后Deck . getcard()从列表中返回一张卡片,而不是随机地创建它。

See what you think of the following:

看看你是怎么想的:

import random

class Deck():
    def __init__(self):
        self.cards = [Card(f,s) for f in Card.FACE for s in Card.SUIT]
        self.shuffle()

    def shuffle(self):
        random.shuffle(self.cards)

    def getCard(self):
        return self.cards.pop()

class Card():
    # Class static data
    FACE = ('A',   '2',   '3',     '4',    '5',    '6',   '7',     '8',     '9',    '10',  'J',    'Q',     'K')
    NAME = ('Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King')
    RANK = (11,    2,     3,       4,      5,      6,     7,       8,       9,      10,    10,     10,      10)
    SUIT = ('Clubs','Diamonds', 'Hearts', 'Spades')

    def __init__(self, face, suit):
        ind = Card.FACE.index(face)
        self.__face = Card.FACE[ind]   # the long way around, but keeps it consistent
        self.__name = Card.NAME[ind]
        self.__rank = Card.RANK[ind]

        ind = Card.SUIT.index(suit)
        self.__suit = Card.SUIT[ind]

    def getFace(self):
        return self.__face

    def getName(self):
        return self.__name

    def getRank(self):
        return self.__rank

    def getSuit(self):
        return self.__suit

    def __str__(self):
        return "%s of %s" % (self.__name, self.__suit)

    def __repr__(self):
        return "%s%s" % (self.__face, self.__suit[:1])

class Player():
    def __init__(self):
        self.cards = []

    def drawCard(self, deck):
        self.cards.append(deck.getCard())

    def drawCards(self, deck, num=2):
        for i in range(num):
            self.drawCard(deck)

    def getRank(self):
        return sum( c.getRank() for c in self.cards )

    def __str__(self):
        cards = ', '.join(str(c) for c in self.cards)
        return  "%s: %d" % (cards, self.getRank())

    def __repr__(self):
        return ' '.join([repr(c) for c in self.cards])

class Game():
    def __init__(self):
        self.deck = Deck()
        self.player1 = Player()
        self.player2 = Player()

    def test(self):
        self.player1.drawCards(self.deck, 2)
        print "Player 1:", self.player1

        self.player2.drawCards(self.deck, 2)
        print "Player 2:", self.player2

def main():
    g = Game()
    g.test()

if __name__=="__main__":
    main()

#3


0  

rank1 = Card.Card.getRank(card1)

This looks like you're trying to call the getRank as a static method. getRank is expecting an instance of itself as the first parameter. This usually means you have a Card object, but the way you call it above, you don't have an object to pass it. I'ms urprised it even lets you call it like that. That should give you an incorrect number of arguments error.

这看起来像是你试图把getRank称为静态方法。getRank希望将自己的实例作为第一个参数。这通常意味着您有一个卡片对象,但是您在上面调用它的方式,您没有一个对象可以通过它。我甚至让你这样称呼它。这会给你一个错误的参数错误数。

Post more code, but it seems like you have serious fundamental problems with your design.

发布更多的代码,但似乎你的设计有严重的基本问题。

Update:

更新:

What's this?

这是什么?

RANK= ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]*FOUR

Why do you need a list of 4 duplicates of your ranks?

为什么你需要一份名单,你的排名是4个副本?

#4


0  

Here is another approach to make a deck of cards

这是另一种制作扑克牌的方法。

from itertools import product

card_values = (
    ("1", "1", 1),
    ("2", "2", 2),
    ("3", "3", 3),
    ("4", "4", 4),
    ("5", "5", 5),
    ("6", "6", 6),
    ("7", "7", 7),
    ("8", "8", 8),
    ("9", "9", 9),
    ("10" ,"10", 10),
    ("Jack", "J", 10),
    ("Queen", "Q", 10),
    ("King", "K", 10),
    ("Ace", "A", 11))

card_suits = ("Spades", "Clubs", "Hearts", "Diamonds")

class Card(object):
    def __init__(self, name, short_name, rank, suit):
        self.name = name
        self.short_name = short_name
        self.rank = rank
        self.suit = suit  

cards = []
for (name, short_name, rank), suit in product(card_values, card_suits):
    cards.append(Card(name, short_name, rank, suit))

#5


0  

You could reduce the amount and complexity of your code by using a Python dictionary. If you did this, your getRank() function could look something like the following:

您可以使用Python字典减少代码的数量和复杂性。如果您这样做了,您的getRank()函数可能看起来如下:

class Card(object):
    RANK = {"A":1, "2":2,  "3": 3, "4":4,  "5": 5, "6": 6, "7":7,
            "8":8, "9":9, "10":10, "J":10, "Q":10, "K":10}

    def __init__(self, draw): # just for example
        self.__rank = draw

    def getRank(self):
        self.__rank = Card.RANK[self.__rank]
        return self.__rank
    #  ...

print Card('A').getRank()
# 1
print Card('4').getRank()
# 4
print Card('J').getRank()
# 10
print Card('K').getRank()
# 10