Loops in Python¶
Ever been in the position where you have to do the same thing again, and again, and again. It’s painful and it feels like there must be a better way. There is, it’s called a loop.
For loops in python¶
The main loop that environmental scientists will use is a for loop. The standard format for a for loop is:
for i in iterable:
action
let’s break that down. The iterable could be any python iterable or iterator (for now don’t worry about the difference), for instance a list. Python will then create a variable (i) pointing to the first object in the list. Next python will then take some action that is in the indented (4 spaces again) line of code. After all the action code if completed python will then set i to the second item in the list and repeat. A simple working example is:
In [1]: menu = ['Egg and Spam', # the iterable
...: 'Egg, bacon and Spam',
...: 'Egg, bacon, sausage and Spam',
...: 'Spam, bacon, sausage and Spam',
...: 'Spam, egg, Spam, Spam, bacon and Spam',
...: 'Spam, Spam, Spam, egg and Spam',
...: 'Spam, Sausage, Spam, Spam, Spam, Bacon, Spam, Tomato and Spam',
...: 'Spam, Spam, Spam, Spam, Spam, Spam, baked beans, Spam, Spam, Spam and Spam']
...:
In [2]: for dish in menu: # dish is the new variable
...: print(dish) # print is the action
...:
Egg and Spam
Egg, bacon and Spam
Egg, bacon, sausage and Spam
Spam, bacon, sausage and Spam
Spam, egg, Spam, Spam, bacon and Spam
Spam, Spam, Spam, egg and Spam
Spam, Sausage, Spam, Spam, Spam, Bacon, Spam, Tomato and Spam
Spam, Spam, Spam, Spam, Spam, Spam, baked beans, Spam, Spam, Spam and Spam
In [3]: print("I don't like spam!")