#!/usr/bin/env python # coding: utf-8 # # Loops and Conditionals # # ### Other resources # # Python course at https://codecademy.com # # Python flow control tutorial https://docs.python.org/3/tutorial/controlflow.html # ## Loops # The `range()` command offers an easy way to loop over a sequence of numbers. Remember that Python is 0 indexed. # In[1]: for i in range(10): print(i) # We can also loop over anything that is iterable, this includes lists, tuples, and dictonaries. # In[2]: alist = ['a', 'b', 'c'] # In the loop below `aletter` takes on each value of `alist` every cycle through the loop. # In[3]: for aletter in alist: print(aletter) # There are also `while`-loops, but the syntax is not as clear as `for`-loops and there is always a danger of entering an infinite loop. # In[4]: i=0 mybool = False while mybool is not True: print(i) i += 1 if i > 10: mybool = True # I prefer `for`-loops with a fixed number of iterations and a `break` statement to replicate the logic of `while`-loops, but protecting from infinite cycles. # In[5]: for i in range(100): print(i) if i > 10: break # Here is an example of a conditional statement with `and` or `or` logic. # In[6]: for i in range(100): if i < 10 or i > 20: print(i) else: print("Hello!") # Python offers a clean syntax for testing if an item is stored in a list, tuple, or dictionary. # In[7]: alist = ['a', 'b', 'c'] if 'd' not in alist: print("True!!!!") else: print("False!!!!")