Python Crash Course Functions, Modules Bachelors V1.0 dd 20-01-2014 Hour 1

Click here to load reader

  • date post

    29-Dec-2015
  • Category

    Documents

  • view

    219
  • download

    4

Embed Size (px)

Transcript of Python Crash Course Functions, Modules Bachelors V1.0 dd 20-01-2014 Hour 1

  • Python Crash CourseFunctions, ModulesBachelorsV1.0dd 20-01-2014Hour 1

  • Introduction to language - functionsWhat are functionsA function is a piece of code in a program. The function performs a specific task. The advantages of using functions are:Reducing duplication of codeDecomposing complex problems into simpler piecesImproving clarity of the codeReuse of codeInformation hiding

    Functions in Python are first-class citizens. It means that functions have equal status with other objects in Python. Functions can be assigned to variables, stored in collections or passed as arguments. This brings additional flexibility to the language.

    Function typesThere are two basic types of functions. Built-in functions and user defined ones. The built-in functions are part of the Python language. Examples are:dir(),len()orabs().

  • Introduction to language - functions>>> def my_func(x, y, z): ... a = x + y ... b = a * z ... return b ... >>>Defining FunctionsHere are simple rules to define a function in Python:Function blocks begin with the keyworddeffollowed by the function name and parentheses ( ).Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.The code block within every function starts with a colon : and is indented.The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.>>> my_func(1.0, 3.0, 2.0) 8.0 >>> my_func(1.0, 3.0, 1.0) 4.0 >>> my_func(5.0, 0.0, 1.0) 5.0 >>> my_func(2.0, 0,0 3.0) 6.0

  • Introduction to language - functions#!/usr/bin/python

    def f1(): print "f1()" f1()#f2()

    def f2(): print "f2()"Defining FunctionsFunction must be denifed preceding their usage:#!/usr/bin/python

    def f(): print "f() function" def g(): def f(): print "f() inner function" f() f()g()uncommenting f2()will cause a NameErrorwhere to define functionsinner function definition

  • Introduction to language - functionsFunctions are objects>>> def f():... """This function prints a message """... print "Today it is a cloudy day"...>>> f.__doc__'This function prints a message '>>> f()Today it is a cloudy day>>> id(f)140491806602016>>>

    >>> def f():... pass...>>> def g():... pass...>>> def h(f):... print id(f)...>>> a=(f, g, h)>>> for i in a:... print i...

    >>> h(f)140491806602016>>> h(g)140491806602136>>>

  • Introduction to language - functionsFunctions typesalways available for usagethose contained in external modulesprogrammer defined>>> from math import sqrt>>> def cube(x):... return x * x * x ... >>> print abs(-1)1>>> print cube(9)729>>> print sqrt(81)9.0

  • Introduction to language - functionsThe return keywordis used to return valueno return returns None>>> def cube(x):... return x * x * x...>>> def showMessage(msg):... print msg...>>> x = cube(3)>>> print x27>>> showMessage("Some text")Some text>>> print showMessage("O, no!")O, no!None>>> showMessage(cube(3))27>>>>>> n = [1, 2, 3, 4, 5]>>> def stats(x):... mx = max(x)... mn = min(x)... ln = len(x)... sm = sum(x)...... return mx, mn, ln, sm...>>> mx, mn, ln, sm = stats(n)>>> print stats(n)(5, 1, 5, 15)>>>>>> print mx, mn, ln, sm5 1 5 15

  • Introduction to language - functions>>> def fact(n):... if(n==0): return 1;... m = 1;... k = 1;... while(n >= k):... m = m * k;... k = k + 1;... return m;Recursion:>>> def fact(n):... if n > 0:... return n * fact(n-1) # Recursive call... return 1# exits function returning 1>>> print fact(100)>>> print fact(1000)

  • Introduction to language - functions>>> def C2F(c):... return c * 9/5 + 32...>>>>>> print C2F(100)212>>> print C2F(0)32>>> print C2F(30)86>>>Function argumentssingle arguments>>> def power(x, y=2):... r = 1... for i in range(y):... r = r * x... return r...>>> print power(3)9>>> print power(3, 3)27>>> print power(5, 5)3125>>>multiple arguments

  • Introduction to language - functions>>> def display(name, age, sex):... print "Name: ", name... print "Age: ", age... print "Sex: ", sex...>>> display(age=43, name="Lary", sex="M")Name: LaryAge: 43Sex: M>>> display(name="Joan", age=24, sex="F")Name: JoanAge: 24Sex: F>>> display("Joan", sex="F", age=24)Name: JoanAge: 24Sex: F>>> display(age=24, name="Joan", "F") File "", line 1SyntaxError: non-keyword arg after keyword arg>>>Function argumentsnamed argumentsorder may be changeddefault value

  • Introduction to language - functions>>> def sum(*args):... '''Function returns the sum... of all values'''... s = 0... for i in args:... s += i... return s...>>>>>> print sum.__doc__Function returns the sum of all values>>> print sum(1, 2, 3)6>>> print sum(1, 2, 3, 4, 5)15>>>Function argumentsarbitrary number of arguments

  • Introduction to language - functions>>> n = [1, 2, 3, 4, 5]>>>>>> print "Original list:", nOriginal list: [1, 2, 3, 4, 5]>>>>>> def f(x):... x.pop()... x.pop()... x.insert(0, 0)... print "Inside f():", x......>>> f(n)Inside f(): [0, 1, 2, 3]>>>>>> print "After function call:", nAfter function call: [0, 1, 2, 3]>>>Function argumentspassing by reference

    Passing objects by reference has two important conclusions. The process is faster than if copies of objects were passed. Mutable objects that are modified in functions are permanently changed.

  • Introduction to language - functions>>> name = "Jack">>> def f():... name = "Robert"... print "Within function", name...>>> print "Outside function", nameOutside function Jack>>> f()Within function Robert>>> def f():... print "Within function", name...>>> print "Outside function", nameOutside function Jack>>> f()Within function Jack>>>

    Function variablesGlobal and Local

    A variable defined in a function body has a local scope

    We can get the contents of a global variable inside the body of a function. But if we want to change a global variable in a function, we must use the global keyword.>>> name = "Jack">>> def f():... global name... name = "Robert"... print "Within function", name...>>> print "Outside function", nameOutside function Jack>>> f()Within function Robert>>> print "Outside function", nameOutside function Robert>>>

  • Introduction to language - functionsTheAnonymousFunctions:You can use thelambdakeyword to create small anonymous functions. These functions are called anonymous because they are not declared by using thedef keyword.Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.An anonymous function cannot be a direct call to print because lambda requires an expression.Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.#!/usr/bin/python # Function definition is here sum = lambda arg1, arg2: arg1 + arg2;

    # Now you can call sum as a function print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 )

    Value of total : 30 Value of total : 40

  • Introduction to languge - ModulesWhat are modules for?Python modules are used to organize Python code. For example, database related code is placed inside a database module, security code in a security module etc. Smaller Python scripts can have one module. But larger programs are split into several modules. Modules are grouped together to form packages.

    Modules namesA module name is the file name with the .py extension. When we have a file called empty.py, empty is the module name. The __name__ is a variable that holds the name of the module being referenced. The current module, the module being executed (called also the main module) has a special name: '__main__'. With this name it can be referenced from the Python code.

  • Introduction to language - Modules$ cat hello.pydef print_func( par ): print "Hello : ", par return#!/usr/bin/python

    # Import module helloimport hello

    # Now you can call defined function that module as followshello.print_func(Earth")Hello : Earth>>> print __name____main__>>> print hello.__name__hello>>>Importing into the current namespace should be done with care due to name clashes

  • Introduction to languge - ModulesWhen you import a module, the Python interpreter searches for the module in the following sequences: The current directory. If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH. If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/lib64/python2.7/.

    The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the insta