I tried to write a simple python code for adding prefixes. Code below:
import sys
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.
Param = [0]
output = []
# Place your code below this line
i=0
for i in Param:
if Param[i] == "-3":
output.append("Rebar Hook: -3")
elif Param[i] == "-2":
output.append("Rebar Hook: -2")
elif Param[i] == "-1":
ouput.append("Rebar Hook: -1")
elif Param[i] == "1":
output.append("Rebar Hook: 1")
elif Param[i] == "2":
output.append("Rebar Hook: 2")
elif Param[i] == "3":
output.append("Rebar Hook: 3")
elif Param[i] == "8":
output.append("Rebar Hook: 8")
elif Param[i] == "9":
output.append("Rebar Hook: 9")
else:
output.append(Param[i]);
# Assign your output to the OUT variable.
OUT = output
It is because you are not looping the parameters correctly, an dyou have set i to always be 0 and you don’t increment it on each loop.
Params = IN[0] #what is the storage type of this? Number or string?
output = []
for Param in Params:
if Param.AsString() == "-3": #or Param.AsInteger() == -3:
output.Add("Rebar Hook: -3")
OUT = output
In most cases, variables are just assigned by the user and can mean anything they want. Apart from the python built-in types and functions (int, str, float, etc.), Dynamo has two reserved variables: IN and OUT. Outside of the context of the Dynamo Python node, IN and OUT have no inherent meaning in Python. In the code above, I am assigning the first input IN[0] to a variable params. Then, I am using a for loop to access each item contained in the list:
# for each param in list params
for param in params:
Compare this to your original for loop:
# for each i in list [0]
for i in Param:
It is common to use i as a variable name, but this is just convention. However, it is most commonly used in this manner:
for i in range(len(params)):
param = params[i]
This is because range() returns a sequence of integers which can then be used as indexes to access different items in a list. If we take the first 3 items of your list and break down your for loop, this is what’s happening:
Param = ['-2', '9', '-1']
for i in Param: # first i in Param is '-2'
if Param['-2'] == '-3':
etc.
A string cannot be used as an index, so Param['-2'] will raise an error.
Thanks a ton for the detailed explanation. I’m just starting out in python, so im trying to write simple codes in python, also in places where a conventional OOTB nodes would do the job.
I will keep the above points in mind when I write scripts in future. Thanks a lot again