Search this site
Embedded Files
Python by Examples
  • Tutorial
    • Download & Install
      • Install Python on Ubuntu Linux
    • Help
  • Strings
    • comparison
    • Get safe character string
    • str() and repr()
  • argparse
    • ValueError
  • Biopython
    • Examples
      • GC content
      • Inverse seq
      • Read/write fasta
    • Install Biopython
  • Data structures
    • Dictionary
      • get keys
      • Multiple keys
    • Lists
      • 0-based indices
      • List element frequencies
      • Median
  • Debugging
  • Error
    • TabError
  • Error handling
    • Check Python version
    • Type checking (raise)
  • File operations
    • File commands
      • get module path
      • os.rename vs shutil.move
      • tar
    • Files: read & write
      • gzip compression
      • Read csv files
      • strip
  • Functions
  • Loops
    • For loops
    • if else ...
    • List Comprehension
  • Math
    • DataFrame
    • Machine Learning
      • Kernel PCA
    • Matrix Calculations
      • Plot
    • Statistics
    • types
  • Packages
    • Create own modules
    • Import Modules
      • Check modul version
    • Install packages
    • python script
  • Parallel processing
    • pool.map - multiple arguments
  • Plot
    • barplot
    • colors
      • rgb2hex
    • matplotlib
      • colormaps
      • Error
      • Transparent colors
  • Print
    • Error
  • System
    • Environment
    • External Commands
  • Time
  • WWW
    • CGI script
    • Download webpage
    • Graphics
Python by Examples

Functions

Python by Examples

In Python, functions are defined by def followed by the function name and arguments and a colon ( : ), next line starts the intended block (4 spaces) of commands.  The result of a function is given back with return. The function definition ends with the end of the intended block.

Simple Example

def my_func(x,y):

    z = x + y

    return z

run the function

z = my_func(2,3)

print(z)

Predefined default argument values

def my_func(x=2,y=3):

    return x+y

z = my_func()

Keyword arguments

better readable;  argument order can be changed

z = my_func(x=2,y=3) # same as

z = my_func(2,3) 

Multiple results

def my_func(x=2,y=3):

    return x+y, x-y, x*y

z_sum, z_sub, z_prod = my_func(x,y)

Many arguments

to catch non-keywords arguments

def my_func(*args):

    print(args)

to catch keyword arguments

def my_func(**args):

    print(args)

z = my_func(a='test',b='m1',c=4,d=10)

Help description

def my_func(x,y):

    '''

    Example of a python function

    '''

    z = x + y

    return z

help(my_func)

Google Sites
Report abuse
Page details
Page updated
Google Sites
Report abuse