Python functions: simple example
Section 3 March 22nd, 2007Python subroutines do not exist. Everything is a function, all functions return a value (even if it’s None), and all functions start with def. This statement is from Dive into Python, a book on Python programming available for free. As mentioned Python functions start with the word def, which is followed by the function name that is followed by the arguments the function receives in between parentheses. Something like
def my_first_function(somevalue):
Usually Python coders (sometime called Pythonistas, among others), following the Python coding style (that states: Function names should be lowercase, with words separated by underscores as necessary to improve readability.) name their functions with words spearated by underscores. And we are going to use this style here, whenever a function becomes handy. The parameters passed to the function (above somevalue) do not have a datatype, Python should handle it whatever is being passed. It is also attribute of your code to handle the parameter/value passed inside the function and avoid errors. Functions also follow the same identation of normal programming and the line after the decalaration should be idented with four spaces
def my_first_function(somevalue):
do_something
So, let’s warmup with functions. The following script is just the start: it adds a poly-T tail to a DNA sequence. We are going to use our old friend AY162388.seq. I will be back after the script
#! /usr/bin/env python
def add_tail(seq):
result = seq + 'TTTTTTTTTTTTTTTTTTTTT'
return result
dnafile = 'AY162388.seq'
file = open(dnafile, 'r')
sequence = ''
for line in file:
sequence += line.strip()
print sequence
sequence = add_tail(sequence)
print sequence
Not very useful, at first sight, but gives us an impression of what a function looks like. Basically we define a function add_tail that receives seq as a parameter. Don’t worry about variable scope now, we will see it later. The rest of the script is just like things we saw before, except for the line sequence = add_tail(sequence). Here we are saving memory (yep, not that much and not even impressive) by assigning the return value of the function to the same string where we have the sequence stored. Run the scritp and get ready for the command line arguments.
October 24th, 2007 at 4:04 am
A comment not really for programming:
I like the statement of ‘a function –> a value’. A script is made with a purpose to fulfill a specific task through all kind of functions that surly return all kins of values, that all together orchestrated for fulfilling the task.
If we say a human life is like a script, then surely a human life is for a purpose. Then all our activities are like functions that return values, that orchestrated for life purpose. But if human lost the sense of purpose for life, then whatever we do would become meaningless for no major goal to fulfill.
Just a thought.