Mouse click is missed

Hello,
I have eight shapes, and I put a loop to detect the mouse clicked, it failed. When I click the mouse, the program can not detected my mouse. As the program skipped the if statement.
Here’s some example code:


cards = [card_0, card_1,card_2, card_3, card_4,card_5,card_6,card_7]
myMouse = event.Mouse()

clicked=False
line_0.draw()
line_1.draw()
line_2.draw()
line_3.draw()
line_4.draw()
line_5.draw()
line_6.draw()
line_7.draw()
card_0.draw()
card_1.draw()
card_2.draw()
card_3.draw()
card_4.draw()
card_5.draw()
card_6.draw()
card_7.draw()
win.flip() 
while not clicked: 
    # check the list of shapes
    for n,card in enumerate(cards):
        if myMouse.isPressedIn(card):
            clicked = True
            response = n  
            break # exit this loop
    else: # this runs once at the completion of the for loop
        time.sleep(0.01)
        response=n*100
    print response    
    myMouse.clickReset() 

Any help would be much appreciated!

NanShan

Your code surely has a syntax error (the else... statement isn’t connected to an if... and from what’s written in the comment I don’t think you’re wanting the if...just above)

As to why it doesn’t act as you expect I think it’s probably that you don’t allow any time between clickReset() and isPressedIn(). Try without the reset line.

It’s one of those very useful but often overlooked Python features that loops have else statements too:

http://book.pythontips.com/en/latest/for_-_else.html

Ha! I stand corrected! And every day’s a school day! :slight_smile:

I find it a very strange concept to give a for-loop an else clause. Really unintuitive to read (maybe just because I’ve not seen that in any other language ever).

It comes into its own in edge cases like @NanShan’s sort of construction: the else clause is executed when a loop terminates naturally, but not when if it is prematurely terminated with a break statement.

But I certainly think that using the name else wasn’t ideal, as it suggests something alternative to the loop rather than a natural consequence of it. Maybe it should have been something like end maybe. But this StackOverflow answer gives a nice take on how to interpret it:

When I removed the myMouse.clickReset() , it succeed. Thank you Jon!

Hi Michael,

Thanks for the info. You are right, the else and break wasn’t ideal here, I will correct it.

Hi @NanShan, don’t take that as a comment on your code at all, rather we were talking about the design of the Python language itself and how the else construction is a bit usual. That’s no reason for you not to use it :slight_smile: