Is it possible to have too many 'and' in an if statment?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Dumuz

I’m trying to make Godot do a simple search within a 2d area, but it never seems to work and I’m wondering if it’s because if there are too many 'and’s in an if statement, that it’s just breaking it. Here’s what I have:

vec is a Vector2 position from a node.

area is an array with [x1,x2,y1,y2]. My boundary lines.

if vec.x > area[0] and vec.x < area[1] and vec.y > area[2] and vec.y < area[3]:
		print("---Stuff in the way ---")

Four ands are not going to break an if statement. I don’t see anything wrong with your code. There’s probably something wrong with one of the variables. Also, you can use Rect2’s has_point method to accomplish what you want with no ands.

exuin | 2021-06-01 19:40

Thanks for your input.

Dumuz | 2021-06-01 20:15

:bust_in_silhouette: Reply From: timothybrentwood

It’s not possible to have too many ands in an if statement. Rewrite the code like this and you can see where it’s failing:

if vec.x <= area[0]:
    printt("x1 fail", vec, area)
elif vec.x >= area[1]:
    printt("x2 fail", vec, area)
elif vec.y <= area[2]:
    printt("y1 fail", vec, area)
elif vec.y >= area[3]:
    printt("y2 fail", vec, area)
else:
    print("---Stuff in the way ---")

You can replace the printt() statements with pass statements once you figure out where in your code the issue is coming from.

As a general rule of thumb, you want to have only one boolean operator (and or or) per if condition in order to keep your code clean and readable. Writing deductive if statements such as the one I wrote above is a great way to make code more readable and maintainable.

“This code is also slightly more performant because as soon as one condition fails it doesn’t evaluate the rest of the conditions”

gdscript (and most other language) does short circuiting, which means as soon as the condition fails the and is not evaluated.

Also the if can be cleaned up using ().

E.g.

if (vec.x > area[0] and vec.x < area[1]) and (vec.y > area[2] and vec.y < area[3]):
    ....
    pass

wyattb | 2021-06-01 23:57

Thank you wyattb! I am aware of what short circuiting is, but I wasn’t aware that gdscript used short circuiting. I edited my answer accordingly.

timothybrentwood | 2021-06-02 15:14