7
while x < len(Hand):
    while y < len(Hand):
        if Hand[x][0] == Hand[y][0] and y != x:
                sameRank += 1
        y += 1
    x += 1

It highlights a space right before the "if" and says syntax error...Makes no sense.

  • 7
    Might be indentation problem.. Have you checked it correctly?? – Rohit Jain Oct 02 '12 at 18:54
  • Checking it right now. Indenting is fine. –  Oct 02 '12 at 18:55
  • 7
    This is a really terrible way to loop over something in Python. Use ``for`` and loop over the items, not indices. As to your problem, please post the actual error, it makes things easier. – Gareth Latty Oct 02 '12 at 18:55
  • 3
    I am guessing that the `if` block is indented to the same level as the `while` block. Check to make sure you're not mixing tabs and spaces too. – cdhowie Oct 02 '12 at 18:56
  • 1
    post the whole traceback here. – Ashwini Chaudhary Oct 02 '12 at 18:56
  • 1
    Let me guess, direct translation of C idiom `for (i = 0; i < 5; i++) {}`. This isn't C. Use `for elem in hand:` instead. – Konrad Borowski Oct 02 '12 at 18:57
  • 6
    `sum(1 for x in Hand for y in Hand if x[0] == y[0] and y!=x)` – Andy Hayden Oct 02 '12 at 18:58
  • When I click run module, I get a pop up window saying "There's an error in your program: Invalid Syntax", and it highlights the space behind the if in red. –  Oct 02 '12 at 19:05
  • What is the error message? Paste it all here. – brandizzi Oct 02 '12 at 19:06
  • There is no message, it's a pop up... –  Oct 02 '12 at 19:08
  • 2
    What interpreter? Also, it will sound dumb, but starting from your top line: go to the end of line, delete the line break and all spaces, then retype the linebreak and re-indent the following line. Repeat for all lines. – selllikesybok Oct 02 '12 at 19:15
  • 2
    Try `for line in open("yourfilename.py"): print repr(line)`, and look for characters which might look like spaces which aren't, like "\x00" or "\xa0". – DSM Oct 02 '12 at 19:40

3 Answers3

8

I don't see any errors here, but it's possible that you're indenting the block below your if statement too much. Notice that the rest of your program uses 4 spaces to indent? Try reducing the indentation to just 4 spaces and see if it runs.

Your code does have a logic error, however. You won't loop through y for each x if you don't reinitialize y at the start of each x.

Here's the example code I ran with the fix for the logic error:

def example():
    Hand = [[1],[2],[3],[3],[4],[5],[2],[2],[1]]
    x = 0 
    sameRank = 0 

    while x < len(Hand):
        y = 0
        while y < len(Hand):
            if Hand[x][0] == Hand[y][0] and y != x:
                sameRank += 1
            y += 1
        x += 1

if __name__ == "__main__":
    example()

Finally, this code can be made a lot more readable by being more "pythonic." Consider this:

def example():
    Hand = [[1],[2],[3],[3],[4],[5],[2],[2],[1]]
    sameRank = 0 

    for x in Hand:
        for y in Hand:
            if x[0] == y[0] and y != x:
                sameRank += 1

if __name__ == "__main__":
    example()

This code iterates over the contents of Hand rather than incrementing temporary integer variables which you then use with the index operator. It's better because there are fewer "maintenance" lines (such as x += 1), it is more readable, and it is more type-insensitive as it will work with any iterable object containing lists.

Or maybe even (per hayden's comment) this:

def example():
    Hand = [[1],[2],[3],[3],[4],[5],[2],[2],[1]]
    sameRank = sum(1 for x in Hand for y in Hand if x[0] == y[0] and y!=x)

if __name__ == "__main__":
    example()

This code combines a call to the sum function with the generator expression 1 for x in Hand for y in Hand if x[0] == y[0] and y!=x. The expression returns a generator which yeilds 1 for each item in your list that matches your criteria, and the sum function adds up all these 1's, thereby giving you the value you're after for sameRank.

Take a look at this article for a good overview of python idioms.

Finally, I'm not sure what editor you're using, but it sounds like it's masking the real problem if you're getting dialog boxes instead of messages and tracebacks straight from the interpreter's stderr/stdout. Sometimes too much help from your editor is a really bad thing when you're trying to learn. I personally use Vim, but this is probably a bit much to ask of a beginner. I don't have much experience with IDLE (it might even be what you're using), but I've heard good things about using it as a learning tool. However if you're doing serious development you'll quickly outgrow it. Either way, if you do use IDLE get used to running your programs from the command line rather than from IDLE itself. I personally find this gives me better feedback in a lot of cases. Finally there's the PyDev IDE (built on Eclipse), which is especially useful for its robust built-in visual debugging. This might be a good choice, but it is indeed a heavyweight option and I'd put it at an "intermediate" level of difficulty to learn if you aren't already familiar with Eclipse. If you are familiar with Eclipse, you'll be right at home with PyDev.

Ben Burns
  • 14,978
  • 4
  • 35
  • 56
  • If I copy and paste your code, correct the indentation problem, and provide dummy data, it works fine for me. You need to update your question with more of your program if this isn't the solution. – Ben Burns Oct 02 '12 at 19:21
  • Python does not care *how much* a line is indented, as long as all lines at that level are indented the same. – Ethan Furman Oct 02 '12 at 20:51
1

It's possible you have a space-like character before the if - I used to get this when using TextMate, where alt+space would insert a non-breaking-space Unicode character instead of a regular space.

Do you have something like # coding: utf-8 at the start of your file? If so, remove it, and you might get a better error message.

Incidentally, without using sum/generation expressions (which might be more confusing than helpful to something learning Python), your loops can be simplified like so:

for x in range(len(Hand)):
    for y in range(len(Hand)):
        if Hand[x][0] == Hand[y][0] and y != x:
                sameRank += 1
dbr
  • 165,801
  • 69
  • 278
  • 343
  • Better to interate over the iterable, rather than to create two new iterables on which to index your existing iterable, no? I find it very rare that I actually need the range/xrange builtins. Extra, extra rare that I need them in which to create a temporary value for an index. Typically I only do that when also using the skip param. – Ben Burns Oct 03 '12 at 15:24
0

Sometimes a mix of tabs and spaces will trip python up - say, if your while loops are indented with tabs, and your if statements use spaces instead. And although the if statement may now be indented correctly, it may still help to check all of the other lines in your snippet to make sure they're all being indented the same way.

A few ways your editor may be able to help:

  • inserting multiple spaces instead of tabs when you hit the tab button
  • showing whitespace characters, so you can see easily if it's four spaces or a tab character
  • search and replace the tab character (\t, if your editor supports searching by regular expressions) and swap them with four spaces, or vice versa.

If your editor supports none of those things, I suggest trying out Programmer's Notepad or Notepad2, if only to help with diagnosing these kinds of issues.

If that sounds unreasonably picky, welcome to programming! It can be frustrating for the best of us. Pick which version you prefer (spaces or tabs), and stick with it. There are also many ways to make this a cleaner piece of code in Python, mentioned above, but it's a good idea to get used to the spacing issues as well.

Hannele
  • 9,301
  • 6
  • 48
  • 68
  • 1
    Spaces. Pick up spaces. Every time you indent with tabs, God kills a kitten. Two if you're indenting python code with tabs. See PEP-8. http://www.python.org/dev/peps/pep-0008/#tabs-or-spaces – Ben Burns Oct 03 '12 at 15:23
  • I'm terrible, I waffle about this (so annoying to have to delete those multiple spaces!), but I am coming around to spaces (so annoying to set tab lengths, spaces just work in everything!). – Hannele Oct 03 '12 at 21:29
  • Yeah, I had the same internal struggle over it. If you use an editor that makes it simple for you, you won't turn back. – Ben Burns Oct 04 '12 at 02:36