red_always_mafia - 4 months ago 8

Python Question

So when i try to run this, i get Invalid syntax on the second if statement, highlighting the colon. I don't understand why this is occurring, as far as i can see, they're basically the same. So why does the second if statement return invalid syntax but the first doesnt?

`for event in pygame.event.get():`

if event.type == MOUSEBUTTONDOWN :

if ROption1Exists == True:

rx, ry = event.pos

if rx >= (100*((X+3)+1)) and rx <= (100*((X+3)+2)) and ry >= (100*(Y+1)) and ry <= (100*(Y+2)):

print('babies')

VarReset()

Pos = ((X+3), Y)

if ROption2Exists == True:

rx, ry = event.pos

if rx >= (100*((X-3)+1)) and rx <= (100*((X-3)+2)) and ry >= (100*((Y+1)) and ry <= (100*(Y+2)):

print('babies')

VarReset()

Pos = ((X-3), Y)

Answer

You have a parenthesis balance problem:

```
if rx >= (100*((X-3)+1)) and rx <= (100*((X-3)+2)) and ry >= (100*((Y+1)) and ry <= (100*(Y+2)):
# 1 23 2 10 1 23 2 10 1 23 21 2 3 21
# ^ all closed ^ all closed ^ uhoh
```

You have one opening parenthesis too many, or one closing parenthesis too few.

You can cut back a little on all those parenthesis, the following suffices:

```
if rx >= 100*(X-2) and rx <= 100*(X-1) and ry >= 100*(Y+1) and ry <= 100*(Y+2):
```

You can *chain* the comparison operators:

```
if 100*(X-1) >= rx >= 100*(X-2) and 100*(Y+2) >= ry >= 100*(Y+1):
```

where `100*(X-1) >= rx >= 100*(X-2)`

is logically the same as `100*(X-1) >= rx and rx >= 100*(X-2)`

but `rx`

is evaluated only once; all you had to do was invert the `<=`

operators by swapping the operands.

Note that testing for equality to `True`

is *rarely* required; just drop the `== True`

from your `if`

statements:

```
if ROption1Exists:
```