0

I'm trying to insert a card into the player list. Here's my code and the error I get:

def deal_card():
    """Returns a random card from the deck."""
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    card = random.choice(cards)
    return card

player = deal_card()
print(type(player))
player.insert(deal_card())
print(player)

AttributeError: 'int' object has no attribute 'insert'

I've tried .append and .add. Why does my code throw this error and how do I fix it?

What I want is [ 2, 3, 5]

3
  • 1
    If player = deal_card() then player is a number. You cannot insert a number into a number because number is not a collection. Did you mean to instantiate player as a list of numbers? Commented Aug 31, 2022 at 13:27
  • 1
    So what does print(type(player)) output? Is player a list? According to this code, it's an integer. Commented Aug 31, 2022 at 13:28
  • print(type(player) gives me and "int" Commented Aug 31, 2022 at 13:58

2 Answers 2

0

player = [player] + [deal_card()] print(player)

gives me[3, 5]

thanks

Sign up to request clarification or add additional context in comments.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

this error means you are trying to call insert() method which owned by list data type, while the data type you are trying to use is an Integer. In your deal_card function,

def deal_card():
    """Returns a random card from the deck."""
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    card = random.choice(cards)
    return card

card = random.choice(cards) will give choose a random value from your cards list, in which will return a whatever type that is chosen in cards list, in your cases is an Integer type.

note that insert() must have 2 parameters to be passed for further information, you can read here

if you want to make a list of the chosen random cards i would recommend to use append() and you can try to use a different attribute maybe called card for passing the data, or just directly append the deal_card function since its return a value, here's an example:

# to use append you should already have a list whether its empty or not
player = []
card = deal_card()
# can also use player.append(deal_card()), in that case you won't need the card variable
player.append(card)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.