For Loops, Logic Statements, and Functions#

For loops to perform the same action on the items in a sequence#


To execute a (set of) statement(s) once for each item in a sequence (e.g. a string, list, or tuple), we use a for loop.

The syntax for a for loop is:

for variable in sequence_name:
    statement(s)

The variable accesses each item of the sequence on each iteration. After the sequence name, we find a colon (:). The statement(s) is (are) indented using whitespace.

The loop continues until we reach the last item in the sequence.

Use sequence_name.append(new_item) to save the outputs of the statement(s) in a new sequence: this function adds a new item to the end of an existing sequence. Make sure to first create the new sequence outside of the loop!

Let’s see this in action by printing each item from a list and calculating and saving in a new list.

Exercise 10

Print each nucleotide from this list with nucleotides.

Nucleotides = ["A", "T", "C", "G"]

Exercise 11

Calculate the \(pK_b\) values of aspartate using this list of \(pK_a\) values of aspartate and save them in a new list called pKb_asp.

pKa_asp = [2.10, 3.86, 9.82]

Logic statements to make choices#


Use if, elif, and / or else statements to evaluate a variable and do something if the variable has a particular value.

Operations include:

  • equal to ==

  • not equal to !=

  • greater than >

  • less than <

  • greater than or equal to >=

  • less than or equal to <=

Use and, or, and not to check more than one condition.

Let’s see this in action using conditional statements.

Exercise 12

Determine the charge of a protein based on its pI (e.g. 4.8) and the pH of the solution (e.g. 7.4).

Functions#


A function is a block of code which only runs when it is called. The function needs parameters to run. These are specified after the function name. The syntax for a function is:

def function_name(parameter(s)):
  """
  documentation
  """
  block_of_code
  return value_to_return
  • We first define the function name and paremeters using def.

  • The optional documentation section contains information about what the function does, including the paremeters and what is returned.

  • The code of the function.

  • Use the return statement to let a function return its result. It is possible return more than one variable from a function. These will be returned as a tuple of variables, which may require unpacking as appropriate.

After creating a function in Python we can call it by using the name of the function followed by parenthesis containing parameters of that particular function.

Let’s see this in action by designing a Beer-Lambert law function.

Exercise 13

Create and test a function that calculates the concentration of a solution using the Beer-Lambert law. Parameters include the molar extinction coefficient, absorbance, and cuvette pathlength.