开发者

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 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.)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜