Control constructs
Table of Contents
if statements
if statements are used to execute code when a condition is true.
is_rainy = True if is_rainy: print('Bring your bumbershoot')
Bring your bumbershoot
These can be followed up by an else:
if is_rainy: print('Bring your bumbershoot') else: print('No rain')
Bring your bumbershoot
Note: In Python, whitespace is used to define levels in the code. It is convention to use 4 spaces (not tabs) as the first level of indentation. The second level would be 4 more spaces (8 total) and so on.
If is_rainy to False, the code under the else statement is
executed instead of the code under the if statement.
More conditions can be added with elif.
if is_rainy: print('Bring your bumbershoot') elif is_sunny: print('Bring your hat') else: print('No rain, no sun')
Bring your bumbershoot
Boolean operators
It is common to use boolean operators with if statements.
some_number = 9 print(some_number == 2)
False
Start IPython by typing ipython in a terminal, and try out a few
more comparisons.
!=<>=
Note: Above I am using print to see the results of the
comparison, but if you're in IPython, you don't need to do this.
Using them within an if statement look like this:
if some_number < 10: print('There are less than 10')
There are less than 10
for loops
for loops allow you to iterate over variables.
genes = ['DNJC..uh', 'FOXP2', 'MET7B'] for gene in genes: print('My favorite gene: ' + gene)
My favorite gene: DNJC..uh My favorite gene: FOXP2 My favorite gene: MET7B
for and if statments can be nested.
for gene in genes: if gene != 'MET7B': print(gene + ', what a dumb gene')
DNJC..uh, what a dumb gene FOXP2, what a dumb gene
Controlling for loops
Once a for loop is running, you often want to change the behavior
based on the current iteration. For example, if a certain value is
encountered, skip to the next iteration. This can be done with
continue, which means stop the current iteration of the loop right
here and go to the next iteration. Using continue, we can produce
the exact same results as the last block.
for gene in genes: if gene == 'MET7B': continue print(gene + ', what a dumb gene')
DNJC..uh, what a dumb gene FOXP2, what a dumb gene
Another common behavior is to break out of the loop completely if some
condition is met. break is the command to do this.
lottery_numbers = [888, 301, 405, 772, 332] winning_number = 405 for number in lottery_numbers: print(number) if number == winning_number: print('We have a winner') break
888 301 405 We have a winner
while loops
There are also while loops in python. These allow the code to
continually be executed while a condition is met.
number = 1 while number < 4: print(number) number += 1
1 2 3
Note: The += is an assignment operator. It adds the value to the
current value of the variable and then assigns the new value back to
the variable. It is equivalent to number = number + 1. Similar
operators exist for subtraction (-=), multiplication (*=), and
division (\=).