Elif dynamo python between number

Hi all I am trying to achieve the following :slight_smile:
I would like to get numbers 0-3 depending on the input

-45 to -135 = 0
-45 to 45 = 1
-135 to -180 = 3
45 to 135 = 2
135 to 180 = 3

I am not even sure if that is the simplest way to interpret that

# Enable Python support and load DesignScript library
import clr
clr.AddReference(‘ProtoGeometry’)
***from Autodesk.DesignScript.Geometry import ****

# The inputs to this node will be stored as a list in the IN variables.
dataEnteringNode = IN

# Place your code below this line

numberList = IN[0]

y = []
for x in numberList:
*** if x < 45:***
*** y.Add(1)***
*** elif 45 <= x < 135:***
*** y.Add(2)***
*** elif 135 <= x < 180:***
*** y.Add(3)***
*** elif 0 <= x < -45:***
*** y.Add(1)***
*** elif -45 <= x < -135:***
*** y.Add(0)***
*** elif -135 <= x < -180:***
*** y.Add(3)***

#Assign your output to the OUT variable.
OUT = y

this is the code I have come up with.

[Python Practise.dyn|attachment]
Python Practise Dynamo Forum.dyn (11.1 KB)

Figured it out below if anyone wants the code for something similar

indent preformatted text by 4 spaces

 # Enable Python support and load DesignScript library
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

# The inputs to this node will be stored as a list in the IN variables.
dataEnteringNode = IN

# Place your code below this line


numberList = IN[0]

y = []

for x in numberList:

	if  -180 <= x <= -135:
		y.Add (3)
		
	elif -136 <= x <= -45:
		y.Add (0)
		
	elif -45 <= x <= 45:
		y.Add (1)
		
	elif 45 <= x <= 135:
		y.Add (2)
		
	elif 135 <= x <= 180:
		y.Add (3)


#Assign your output to the OUT variable.
OUT = y
1 Like

This is somewhat of a PSA, as you’ll see many people doing this, but a range is actually redundant in nested conditions like this. All you need is:

if x <= -135:
    y.Add(3)
elif x <= -45:
    y.Add(0)
elif x <= 45:
    y.Add(1)

If x isn’t less than -135 then you know it’s greater. You don’t have to check it again in the next condition.

Also, make sure your limiting values are setup correctly. Your first condition goes up to -135 and your second one starts at -136, meaning you have unnecessary overlap (negative values and all). You also use <= for every condition which means -45 (for example) is inclusive to both conditions.

Again, none of this is technically wrong but it is redundant and slightly misleading.

2 Likes