Grasshopper Python 105
Loops (I)
Loops are a fundamental weapon when dealing with program flow. You’ll want your component to perform a certain action many times over a data-set or to keep on doing something until a condition is met. That’s exactly what loops are for. Let’s see them in action.
Two Types Of Loops
The Fore Each Loop is useful when you want to exactly the same operation to each element within a collection. For instance printing something to the console or just adding all the numbers in a collection. We have to supply an interator value, of the a suitable type for the collection, that will be evaluated at each step of the loop.
This example prints reads a string as a list of letters and prints them independently
myName = "Roberto Molinos"
for letter in myName:
print letter
This example takes a list of numbers and returns the number of elements and the sum of all of them:
buffer = 0
for num in x:
buffer += int(num)
print "There are %d items in the list and their sum is %s" %(len(x),buffer)
This example takes a list of strings and creates a sentence with all the supplied values:
buffer = "My favourite ice cream flavours are:"
for flavour in x:
buffer += str(flavour) + ", "
print buffer
The For loop is useful when we want to keep control of the iteration process, being able modify actions depending on iterator state. Look at this example that will output only elements with even index from a list:
# This script takes a list of input numbers and returns a sublist with the even numbers
# Declare a list to hold even number
evenNumList = []
# make i change between 0 and the length of the x list
for i in range(0,len(x)):
# check if the index is even
if i % 2 == 0:
# if so, append the item to the list
evenNumList.append(x[i])
# Return the list
a = evenNumList
The key here is the declaration of the loop:
Besides, the inner IF statement is checking when the iterator is even, look at it carefully.
Another example, this component will create a Fibonacci series:
# This script creates a the first x numbers of a fibonacci series
# Declare a list and start it with the first two numbers
fiboList = [1,1]
# Check that x is at least 2
if x > 1:
# make i change between 0 and x
for i in range(2,x):
# retrieve the two previous values, add them an assign to a temporary variable
buffer = fiboList[i - 2] + fiboList[i - 1]
# append the value to the list
fiboList.append(buffer)
# Return the list
a = fiboList
Challenge
1. Write a Python component that reads a list of numbers and outputs the largest of them together with its index.
2. Write a Python component that reads a list of numbers and outputs the smallest of them together with its index.