Python 101

Functions

Diogo Silva


Day overview:

Functions

  1. Purpose
  2. The basic recipe and calling a function
  3. Arguments
  4. Variable scopes
  5. Returning values from a function
  6. Lambda (anonymous) function

I/O Input output

  1. Input from user/keyboard
  2. Reading files
  3. Writing files
  4. Closing files

Purpose

Functions - pieces of code that are written one time and reused as much as desired within the program. They:


Purpose




Purpose



And 19 more times to accomodate all other amino acids!!


Purpose



With only 7 lines of code, we are now able to provide the required information for all amino acids and for any input sequence.


The basic recipe



  1. "def" - Functions must start with the "def" keyword.
  2. "name" - The name of the function must not contain special characters or whitespaces
  3. "()" - Parenthesis enclose input parameters or arguments
  4. ":" - The code block within every function starts with a colon and is indented
  5. Documentation [optional] - It is good practice to document your function
  6. "statements" - The actual code block of your function

Function calling




Arguments

A function can be created without arguments,



or using the following types of arguments:


Arguments

Required arguments








Arguments

Required arguments








Arguments

Variable length arguments




Arguments

Default arguments








Arguments

Using argument keywords








Arguments

Considerations when combining different argument types








Namespaces or scope of variables

When writting a program, it is extremely important to know the difference between the local and global scope of the variables

Glogal variables








Namespaces or scope of variables

Local variables








Return

The return keyword is used to return values from a function, which can then be assigned to new variables that are accessible to the whole program




Return

Returning multiple values








Return

Functions always return something

If a function does not contain the return keyword, it will return None




Lambda (anonymous) functions

Lambda is an anonymous (unnamed) function that is used primarily to write very short functions that are a hassle to define in the normal way. Where a regular function would do:



a lambda function:



The lambda function can be used elegantly with other functional parts of the Python language, like map(). In this example we can use it to convert a list of RNA sequences into DNA sequences:




Wrap up

So, we have covered thus far:

/

#