Unknown syntax error
Why do I get a syntax error running this code? If I remove the highlighted 开发者_StackOverflow中文版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())
cards[i] = cards[i].append(random.randint(0,9)
^
Missing closing parenthesis. And the return statement on the next line is incorrectly indented.
Missing a close:
cards[i] = cards[i].append(random.randint(0,9))
- Your
SyntaxError
is due to an unclosed paren aftercards[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 setcards[i]
to be astr
object then try to callappend
on it. Strings don't have anappend
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
.
- When you do need indices, which is very rare, it's usually best to use
- 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 attributeself.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.)
- Make a class that stores the cards as a state with a method called
精彩评论