Grasshopper Python 103
Conditional Statements
Working with single values improves a lot when you can perform what is called conditional logic. This introduces a basic concept called program flow: parts of our code that get executed depending on some conditions. Conditional statements require operators, expressions that compare two (mostly numerical) properties and check for a logical state.
Basic Conditional Statement
if x > y: #Check if x is strictly larger than y
A = x #If so, Assign x to A
else:
A = 0.0 #Assign 0.0 to A
Every conditional statement has a logical test and an action to perform if the test is true. The “else:” is optional and will be executed in case the test is false.
Important: Conditional statements and other flow control expression require we define blocks of code by carefully using indents in our lines. You can use whatever spaces you want but it is better to indent blocks using the TAB key. A minimum condition is that all lines belonging to the same block must be indented the same number of positions.
This is correct:
if x > y:
A = x
B = 0.0
else:
A = 0.0
B = 1.0
This is NOT correct:
if x > y:
A = x
B = 0.0
else:
A = 0.0
B = 1.0
Operators
More info can be found in the corresponding Python Operators
Comparison Operators:
Comparison operators are used to check two elements against each other. Most of the times the elements will be numbers (integers, doubles, floats,…) but also other types, specially when determining if two elements are the same.
Math Operators:
Assignment Operators:
Logical Operators:
Used to perform logical proofs between several comparison tests. Consider A and B as booleans.
Examples:
#Example 0. Copy the contents of the script to your component
if x > 1:
A = x
#Example 1. Copy the contents of the script to your component
if x > z:
A = "large"
elif x <= z and x > y:
A = "medium"
else:
A = "small";
#Example 2. Copy the contents of the script to your component
if x == y:
A = "match!"
elif x < y:
A = "smaller"
else:
A = "bigger"
#Example 3. Copy the contents of the script to your component
if x != 0.0:
if x < y:
x += z # the same as x = x + z
else:
x -= z # the same as x = x - z
A = x
Challenge
1. Write a component that filters a lists of input integers and returns only those which are even numbers.
2. Write a component that filters a list of input integers and returns only those which are a multiple of a Y integer.