anon_misid
anon_misid

Reputation: 87

How to fix TypeError: 'str' object cannot be interpreted as an integer in Python

I am writing a code where the program draws the amount of cards that was determined by the user. This is my code:

from random import randrange

class Card:

def __init__(self, rank, suit):
    self.rank = rank
    self.suit = suit
    self.ranks = [None, "ace", "2", "3", "4", "5", "6", "7", "8",
    "9", "10", "jack", "queen", "king"]
    self.suits = {"s": "spades","d": "diamonds","c": "clubs","h": "hearts"}

def getRank(self):
    return self.rank

def getSuit(self):
    return self.suit

def __str__(self):
    return "%s of %s" % (self.ranks[self.rank], self.suits.get(self.suit))

def draw():
    n = input("Enter the number of cards to draw: ")

    for i in range(n):
        a = randrange(1,13)
        b = randrange(1,4)
         
        c=Card(a,b)
        print (c)

draw()

And this is the error I keep getting:

Traceback (most recent call last):
  File "main.py", line 31, in <module>
    draw()
  File "main.py", line 24, in draw
    for i in range(n):
TypeError: 'str' object cannot be interpreted as an integer

Any help would be appreciated.

Upvotes: 0

Views: 7480

Answers (3)

Ahx
Ahx

Reputation: 7985

The error is here:

n = input("Enter the number of cards to draw: ")

The n variable type is: str

enter image description here

One solution is:

n = int(input("Enter the number of cards to draw: "))

Here is the full code:

from random import randrange


class Card:
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit
        self.ranks = [None, "ace", "2", "3", "4", "5", "6", "7", "8",
                      "9", "10", "jack", "queen", "king"]
        self.suits = {"s": "spades", "d": "diamonds", "c": "clubs", "h": "hearts"}

    def getRank(self):
        return self.rank

    def getSuit(self):
        return self.suit

    def __str__(self):
        return "%s of %s" % (self.ranks[self.rank], self.suits.get(self.suit))


def draw():
    n = int(input("Enter the number of cards to draw: "))

    for i in range(n):
        a = randrange(1, 13)
        b = randrange(1, 4)

        c = Card(a, b)
        print(c)


draw()

Output is:

Enter the number of cards to draw: 5
2 of None
jack of None
2 of None
4 of None
ace of None

Upvotes: 2

Tomas Giro
Tomas Giro

Reputation: 4267

Try converting the string to an integer:

for i in range(int(n)):

In addition, to handle input errors:

try:
    n = int(n)
except ValueError:
    print('{} was not recognized as an integer.'.format(n))

Upvotes: 2

circo
circo

Reputation: 166

You can use int() to convert the string into an integer. You might also want to use some form of error handling to catch any exceptions in case the user enters something that cannot be parsed.

Upvotes: 2

Related Questions