8.4. Boolean functions

Whenever a condition is too complex, you can write a boolean function.

Boolean function

Boolean functions are function that return truth values (in Python either False or True).

It is good style to give them a name that indicates its nature, often the function name starts with is.

Here is an example that tests if a character is a valid amino acid:

>>> from string import *

>>> def isAminoAcid(aa):
...     AA = upper(aa)	
...     if AA < 'A' or AA > 'Z':
...       return False
...     if AA in 'JOU':
...       return False
...     return True
      
you can also write it as follow:
>>> from string import *

>>> def isAminoAcid(aa):
...     AA = upper(aa)	
...     if AA < 'A':
...        ok =  False
...     elif AA > 'Z':
...        ok = False
...     elif AA in 'JOU':
...        ok = False
...     else:
...        ok = True
...     return ok
      
or using boolean operators:

Example 8.2. Function to check whether a character is a valid amino acid

>>> def isAminoAcid(aa):
...     return ('A' <= aa <= 'Z' or 'a' <= aa <= 'z') and aa not in 'jouJOU' 
	

Using this function makes your code easier to understand because the function name expresses what you want to test:

>>> prot = 'ATGAFDWDWDAWDAQW'
>>> oneaa = prot[0]

>>> if isAminoAcid(oneaa):
...    print 'ok'
... else:
       print 'not a valid amino acid'
ok