matt1024
matt1024

Reputation: 201

Unknown syntax error

Why do I get a syntax error running this code? If I remove the highlighted section (return cards[i]) I get the error highlighting the function call instead.

Please help :)

def dealcards():
    for i in range(len(cards)):
        cards[i] = ''
        for j in range(8):
            cards[i] = cards[i].append(random.randint(0,9)
    return cards[i]


print (dealcards())

Upvotes: 0

Views: 1698

Answers (3)

Mike Graham
Mike Graham

Reputation: 76683

  • Your SyntaxError is due to an unclosed paren after cards[i] = cards[i].append(random.randint(0,9)
  • When you clear that up, you'll find you will get an AttributeError when you call this function. You set cards[i] to be a str object then try to call append on it. Strings don't have an append method.
  • You loop over indices and change each place in cards. This is usually a sign you're doing something wrong; it's more typical in Python simply to make a new list.
    • When you do need indices, which is very rare, it's usually best to use enumerate.
  • More to the point about the last one.....this function modifies a global, cards. Using functions to mutate global state is a bad thing. There are two possibilities that would almost certainly be better:
    • Make a class that stores the cards as a state with a method called deal_cards which mutates some attribute self.cards or whatever. (Probably the way to go.)
    • Make a function that accepts cards as an argument and returns a new list. (Probably not the way to go, but improves modularity, maintainability, and testability over your current technique.)

Upvotes: 1

AndiDog
AndiDog

Reputation: 70158

cards[i] = cards[i].append(random.randint(0,9)
                                              ^

Missing closing parenthesis. And the return statement on the next line is incorrectly indented.

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

Missing a close:

cards[i] = cards[i].append(random.randint(0,9))

Upvotes: 1

Related Questions