Docsity

Python Conditional Statements and Functions, Exams of Bioinformatics

Toggle sidebar
bg1
Part 1: Conditional statements
Conditional statements allow for selective execution of code depending on the outcome of a
comparison. Boolean expressions and conditional statements go hand in hand, as we will see in
the exercise.
Boolean expressions
Boolean expressions are expressions that evaluate to either true or false. They are a common
feature of programming languages. The following comparison operators are commonly used in
Boolean expressions.
Comparison Operators:
x == y # x is equal to y
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
x is y # x points to the same object as y (rarely used
)
x is not y # x does not point to the same object as y
A common error is to use = in place of == . = is an assignment operator (i.e. set x = y),
whereas == is a comparison operator (i.e. is x = y).
Assign a volume to the variable vol :
In [1]:
What type of value is the variable? Confirm your answer using the type() function:
In [2]:
When evaulated by the Python interpreter, Boolean expressions that evaulate produce special
values - True if true and False if false. True and False belong to a class of values
called bool .
Out[2]:
int
vol = 100
type(vol)
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Python Conditional Statements and Functions and more Exams Bioinformatics in PDF only on Docsity!

Part 1: Conditional statements

Conditional statements allow for selective execution of code depending on the outcome of a comparison. Boolean expressions and conditional statements go hand in hand, as we will see in the exercise.

Boolean expressions

Boolean expressions are expressions that evaluate to either true or false. They are a common feature of programming languages. The following comparison operators are commonly used in Boolean expressions. Comparison Operators: x == y # x is equal to y x != y # x is not equal to y x > y # x is greater than y x < y # x is less than y x >= y # x is greater than or equal to y x <= y # x is less than or equal to y x is y # x points to the same object as y (rarely used ) x is not y # x does not point to the same object as y A common error is to use = in place of ==. = is an assignment operator (i.e. set x = y), whereas == is a comparison operator (i.e. is x = y). Assign a volume to the variable vol : In [1]: What type of value is the variable? Confirm your answer using the type() function: In [2]: When evaulated by the Python interpreter, Boolean expressions that evaulate produce special values - True if true and False if false. True and False belong to a class of values called bool. Out[2]: (^) int vol = 100 type(vol)

In [3]: Use the == operator to test if vol is equal to 100: In [4]: Use the <= operator to determine if vol is less than or equal to 100: In [5]: Use the != operator to determine if vol is not equal to 100: In [6]: Assign an RNA sequence to two different variables, for example rna1 and rna2 : In [7]: Compare the two RNA sequences to determine if they are equivelent using == : In [8]: Compare the two RNA sequence variable from above using the is operator: In [9]: The is operator at first glance seems similar to == but it is quite different. is tests whether two values point to the same object. The variables rna1 and rna2 point to the same object, a value that python has interned or stored away. But it's dangerous to use is when making comparisons unless you know the object has been interned. Let's look at an example using a type of object we haven't seen yet, a list: Out[3]: (^) bool Out[4]: True Out[5]: True Out[6]: (^) False Out[8]: (^) False Out[9]: False type( True ) vol == 100 vol <= 100 vol != 100 rna1 = 'AUG' rna2 = 'UUU' rna1 == rna rna1 is rna

Note the colon after the conditional statement and the indentation of code that is to be executed if the condition is met. Indentation (tab or 4 spaces) is Python's way delimiting blocks of code within conditional statements and in some other contexts that we will cover later in the course. Determine if the variable num is less than 10 ( < is the Python operator for less than): In [28]:

Logical operators

There are three logical operators in Python, and , or , and not. These operators are often represented by symbols in other programming languages. A nice feature of Python is that it uses the English words for these operators. Assign a number to a variable, such as n : In [29]: Test if the number is greater than 95 but less than 105: In [31]: The expressions on either side of and are evaulated independently, thus we can't write the comparison this way: In [33]: The code above generates errors because < 105 by itself is not an expression that can be evalauted. Number is less than 10 Yes! File "<ipython-input-33-230e87afb517>", line 1 n > 95 and < 105 ^ SyntaxError: invalid syntax if num < 10 : print("Number is less than 10") else : print("Number is not less than 10") n = 100 if n > 95 and n < 105 : print("Yes!") else : print("No!") n > 95 and < 105

Test if n is equal to 100 or 101: In [38]: In the example above with and we saw a harmless syntax error, harmless in that it's an easy fix and we can move on with our code. But what about this: In [39]: A far more dangerous semantics error. Test if n is not equal to 100 or 101 using the not operator: In [64]: As you can probably see, negating something with the not operator often makes code difficult to follow so when possible it should be avoided. Test if n is not eqaul to 100 or 101 using the != operator: In [66]:

Chained conditionals

What if we want to test multiple conditions or execute distinct blocks of code depending on which of multiple possible conditions is true? We can simply add another condition, else if , to an if statement. Python uses the shorthand elif in its syntax for else if (it saves a couple keystrokes). Notice that elif statements also use boolean expressions: n is 100 or 101. n is 100 or 101. n = 100 if n == 100 or n == 101 : print("n is 100 or 101.") n = 5 if n == 100 or 101 : print("n is 100 or 101.") n = 101 if not (n == 100 or n == 101 ): print("n is not 100 or 101.") n = 100 if n != 100 and n != 101 : print("n is not 100 or 101")

Nested conditionals

It is occasionally necessary, or at least more convienent, to nest conditionals within conditionals: if primary expression evaluates to True : block of code else : if secondary expression evaluates to True : block of code else : block of code

try and except

An error detected during execution of code is called an exception. The error message is often ugly and difficult to understand unless you're familiar with Python:

In [82]: try and except provide a convienent way to 'catch an exception' and provide a more informative custom error message. The syntax is as follows: try : block of code except : block of code #(e.g. prints a user friendly error message or returns a value of -1) If the code in the try clause is executable without generating an error, than the code in the except clause, which typically prints a user defined error message is ignored. If an error is generated, than the except clause is executed. try and except can be used to detect different types of exceptions and execute different blocks of code depending on the error. Here's the code from above with an except clause that prints a user friendy error message if an invalid operation is attempted: In [83]: An additional advantage to the try clause is that code outside of it is still executed even if the code within the try clause throws an exception.

TypeError Traceback (most recent call last) <ipython-input-82-c525e6b4d01c> in () 1 n = 'ATG' ----> 2 print(n** 2 ) TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int ' The operation cannot be completed. n is not numerical. n = 'ATG' print(n ****** 2 ) n = 'ATG' try : print(n ****** 2 ) print('Program complete.') except : print("The operation cannot be completed. n is not numerical.")

In [89]: Of course we can store the value returned by len() as a variable: In [91]:

Part 2: Fun with functions!

A function is a block of code that performs a single action that can be reused indefinitely. They provide a great way of breaking code into smaller reusable pieces. And they're fun!

Built-in and user-defined functions

We have seen serveral built-in functions now: print() , len() , input() , type() , float() , etc. Note that the syntax is similar - function_name(arguments). When we call a function, it executes some code using as input arguments passed into the function, such as variables and values, and returns a result. More simply stated, a function takes arguments, executes code, and returns a result. This result is called a return value. For example, the length function len() takes as an argument an object, such as a string, some code runs in the background that determines the number of items in the object, for a string this would the number of characters, and a value is returned. In [92]: See https://docs.python.org/3.7/library/functions.html (https://docs.python.org/3.7/library/functions.html) for a list and description of the ~70 built in functions. Go through the list and explore them on your own. Python makes it easy to create your own functions. These functions are completely portable and can be used in any Python script essentially just like the built-in functions. We can define a function by assigning a name to the function and a block of code to execute - this is referred to as function definition. The syntax is as follows: Out[89]: 6 Out[91]: 6 Out[92]: 12 seq = 'AAAGGA' len(seq) l = len(seq) l len('ATGCATGCTATC')

def function_name(arguments): block of code def is a keyword that is used to indicate that this is a function definition. The first line is called the header and the block of code is called the body and must be indented. Define a function called echo() that prints whatever arugment is passed to it: In [95]: Now we can call our new function just like we would a built-in function: In [101]: Functions always return a value. This particular example prints whatever argument we pass to it, and returns a value. However, the value it returns is None , which is not particularly useful: In [103]: A function that doesn't return a useful value is called a void function.

Returning values

For a function to be useful, it will typically return a value. Here's a function called cat() that concatenates two DNA or RNA sequences passed as arguments: In [104]: The return statement is used to provide a value from a function. The return statement also exits the function so you can only have one return statement and you can not include any code after the return statement. Circus McGurcus Circus McGurcus None def echo(t): print(t) echo("Circus McGurcus") event = echo("Circus McGurcus") print(event) def cat(seq1, seq2): return seq1 + seq

In [115]: If we were to call the function in a script, just as with built-in functions such as len() , a result is returned but it is not printed or acted on. We can store the return value as a variable if that is useful or we could print the return value: In [117]:

Setting default argument values

It is often useful to have default values for one or more arguments. Let's modify the cat() function to concatenate 1-4 sequences: In [120]: The empty values (specified by '' ) asssigned to seq2 - seq4 will be automatically used if the user provides less than 4 arguments: In [121]:

Local vs global variables

Variables assigned within a function cannot be used outside of the function, these are called local variables because they can only be used locally. Variables assigned outide of a function are global, meaning they can be used anywhere: Out[115]: 'dna' dna Out[121]: (^) 'ATGTGA' seq = 'ATGG' base_id(seq) nt = base_id(seq) print(nt) def cat(seq1, seq2 = '', seq3 = '', seq4 = ''): return seq1 + seq2 + seq3 + seq cat('ATG', 'TGA')

In [124]:

Functions within scripts

A function can be defined within a script but the function is not actualy executed unless the function is called. It can be used within the script at any point after it is defined. After the statements within the function are executed, the script will pick up right where it left off when the function was called.

Modules

What if we want to define a function that we can use in other scripts or call in the Python interpretor or jupyter notebook? This is easily done by placing the function, possibly along with related functions, into a seperate document. A document that contains Python function definitions that can be imported into other scripts is called a module and has the extension .py. Copy the code for the cat() and base_id() functions into a new text editor file and save the file as seqedit.py. Document strings and comments will help make your modules and functions easier to read:

num = 5 #global variable assignment def cube(n): num_cube = n ****** 3 #local variable assignment print(num) #print global variable print(num_cube) #print local variable inside function cube(num) #print(num_cube) #print local variable outside function

To call a specific function within the module, use the syntax module_name.function_name() (also called dot notation). Try calling the base_id() function: In [128]: Any function within the module can be called using the syntax above. Reloading a module, which you might have to do if you have an error in the original module, is overly complicated in Python. You first have to import the importlib package (a package is a collection of modules) and then use the reload function contained in the package: In [129]: When you import a module, a new folder pycache will appear in the directory containing the module. This is bytecode generated by the Python interpretor that is used when a function is a called to save time in executing the code.

Where to find information on available modules

There are numerous standard Python modules that can be imported into a program at any time. See https://docs.python.org/3/py-modindex.html (https://docs.python.org/3/py-modindex.html) for a list and descriptions. There are also a of number modules freely available that accomplish routine tasks in biology. See for example BioPython - http://biopython.org/wiki/Documentation (http://biopython.org/wiki/Documentation) and http://biopython.org/DIST/docs/api/module- tree.html (http://biopython.org/DIST/docs/api/module-tree.html). Also see https://pypi.python.org/pypi?%3Aaction=search&term=bioinformatics&submit=search (https://pypi.python.org/pypi?%3Aaction=search&term=bioinformatics&submit=search) for additional Bioinformatics packages.

Testing functions

Out[128]: (^) 'dna' Out[129]: (^) <function importlib.reload(module)> seqedit.base_id('ATG') import importlib importlib.reload

Modules can be imported into the Python interpretor, which provides a useful way of testing functions. Launch the Python interpretor and import the seqedit module and test the cat() function from the previous exercise. When you execute a script in Python, as the initial file executed it is assigned the name main. A module imported into Python is assigned a different name. If you want to make a module that can also act a standalone program, you can use the following syntax to include additional code that is executed only when the module is executed as a script: def modulename() block of code if name == 'main': block of code The block of code in the if statement typically passes arguments to a function in the module and prints the return value of the function. For example: if name == 'main': print(modulename(arguments)) Within a print() statement we can call the function and print the return value.

Assignment 2

Assignment 2 is now available. It is due by 10 am on 10/8.

! Present " Slides # Themes? Help