Control flow
Francisco Pina-Martins
Day Overview:
Today we will go around the basics of control flow:
- What types are there?
- What does it do?
- How do I work with it?
Types:
There are essentially 2 types of flow control:
Conditionals:
"Boolean Operators"
Let's take a short trip back to the land of High School Mathematics:
< » Less than;
<= » Less or equal than;
> » Greater than;
>= » Greater or equal than;
!= » Not equal to;
<> » Not equal to (alternative);
== » Equal to (Note the double "=");
"Boolean expressions"
x is y
x is not y
x in y
x not in y
Conditional Statements:
When are they used?
When we want our program to do different things if a determined condition is met.
How do they work?
Let's look at some pseudo-code:
if «Condition(s) to be met»:
«Do something»
«Do something else»
elif «Another condition»:
«Do something different»
else:
«Do something else enteirely»
«Do something every time,»
«Since this part is not indented»
Take special care with:
- You can have as many "elif"s as you wish;
- You can only have one "else" and it has to be after the last "elif";
Real code example:
Let's look at a real code example:
- Try changing the value of sequence and see the different results.
Likewise, we can use other boolean operators:
- Notice the use of the len() function. It is used to return the length of an object, in this case, the length of the string sequence.
The for loop:
When are they used?
When we want our program to do the same thing to a lot of things.
The for loop will do something for every value in an iterable.
How do they work?
Let's look at another pseudo-code example:
for «item» in «iterable»:
«Do somthing with item»
«Do something else with item»
«Do something after the loop is done»
Take special care with:
- An iterable can be any iterable object, such as:
- A string, a tuple a list or a dictionary;
- Characters in a string;
- Elements of lists and tuples;
- Keys and values of dictionaries;
- Integers and floats are not iterable;
- A list of integers, however is iterable;
Real code example:
Once again, let's look at a real code example:
Running this code will print the numbers from 0 to 3 (remeber python starts to count from 0), each followed by a newline character.
Also make note of the range() function. It is used in this case to create a list of integers from 0 to 5 on the fly. It is a very versatile function, you can read more about it in the documentation.
Another example could be:
Now that was easy, wasn't it? Let's make it a bit more difficult...
Nested loops:
Sometimes we have some code that we want to run x times and some code within that code that we want to run y times.
- In this example we want to find which sequences are common to both lists:
Take special care with:
- Nested loops can look like a good idea at first, but they usually have a great impact on performance. If you are working with large datasets, you are advised to avoid them.
The while loop:
When are they used?
The while loop is used when we want to combine the functions of the if statement and the for loop (sort of).
How do they work?
Here is some more pseudo-code as an example:
while «Condition is true»:
«Do something»
«Do something else»
«Do something after Condition is not true»
Take special care with:
- Make sure the contents of your while loop alter the condition being verified, otherwise you may get caught in an "infinite loop".
Real code example:
Let's look at another real code example:
Running this code will yield the same result as our first for loop, but it's done in a diffrent way.
As you can see, the while loop will test against a condition and run the code in it while the condition is true.
Here's another example (a bit more bio and a bit less abstract). Let's call it an ORF generator:
Wow, wait a minuite, what is this? Let's look at it in parts. (Next slide please!)
The Mighty ORF generator:
import random
This will import the functions from the random module. Don't worry about it for now. We will have more fun with modules later.
Then, we declare our variables: ORF, bases and stops, so far so good.
Finally the loop:
while ORF.endswith(stops) == False:
What this means - "While the variable ORF does not end with any of the content of stops do this:"
ORF += random.choice(bases)
What this means - "Add a random character from bases to ORF."
Here is the documentation for the used functions: endswith(), random.choice().
Can you see something wrong with this?
Deeper into control flow:
Break, continue, else on loops and pass:
- Break
- will immediately stop any for or while loop;
- Continue
- will immediately continue with the next iteration of the loop;
- Else on loops
- will do something after and only the loop is finished. Breaking the loop will not run this code;
- Pass
- will do absolutely nothing;
Real code examples:
(We don't really need pseudo-code for this)
Take special care with:
- The way the range() function was used; In this case we also defined the start of the count;
- The str() function - it will convert any object (in this case an integer) into a string. This is required to concatenate the variables in the print() function;
- Try to change the breakpoint and skippoint variables for different results;
Special type of iteration - dictionaries:
- When "looping" through a dictionary, we can use a special function - items()
What's so special about this?
Note that we are iterating two variables at the same time. This can be tricky to master at first, but it is a very useful function once you've gotten the hang of it.
Take special care with:
- Dictionaries will not preserve the order that the key:value pairs are stored in;
- This means that when you iterate through a dictionary, your key:value pairs can turn up in any order;
- You can do something similar with two (or more) lists by using the zip() function;
Biological examples:
Let's suppose we have a dictionary of 3 lists with several species each and we wish to know in which of these lists (if at all) we can find our species - Homo sapiens
Take special care with:
- Notice that when defining listset, the code is split along several lines; you can read more about this here;
- In line 7, we are calling the values in the dictionary, not the keys;
- Try changing the variable species and see the results;
Biological examples (part II):
In this example we have a string with 3 "columns" divided by tabs ("\t") in python. Let's suppose that we wish to extract the Fst value for each column into a list.
Take special care with:
- The splitlines() type; this built-in will split a string into a list where each element is a line of the string;
- The startswith() function; it is pretty much self explanatory;
- The split() function; it will split a string into a list of words eliminating the separator.
- You have to test this in IDLE or equivalent.
←→/
#