5 Library and Functions
Library are group of functions
5.1 Package Source
5.1.2 PIP
- Package manager python only
- Compile from source
- Stands for Pip Installs Packages
- Python’s officially-sanctioned package manager, and is most commonly used to install packages published on the Python Package Index (PyPI)
- Both pip and PyPI are governed and supported by the Python Packaging Authority (PyPA).
5.2 Importing Library
There are two methods to import library functions:
Standalone Namespace
- import <libName> # access function through: libName.functionName
- import <libName> as <shortName> # access function through: shortName.functionName
Global Namespace
- from <libName> import * # all functions available at global namespace
- from <libName> import <functionName> # access function through: functionName
- from <libName> import <functionName> as <shortFunctionName> # access function through shortFunctionName
5.2.1 Import Entire Library
5.3 Define Function
5.3.1 Function Arguments
By default, arguments are assigned to function left to right
def myfun(x,y):
print ('x:',x)
print ('y:',y)
myfun(5,8)#:> x: 5
#:> y: 8
However, you can also specify the argument assigment during function call
myfun (y=8,x=5)#:> x: 5
#:> y: 8
Function can have default argement value
def myfun(x=1,y=1): # default argument value is 1
print ('x:',x)
print ('y:',y)
myfun(5) # pass only one argument#:> x: 5
#:> y: 1
5.3.2 List Within Function
Consider a function is an object, its variable (some_list) is immutable and hence its reference won’t change, even data changes
def spam (elem, some_list=[]):
some_list.append(elem)
return some_list
print (spam(1))#:> [1]
print (spam(2))#:> [1, 2]
print (spam(3))#:> [1, 2, 3]
5.3.4 No Return Statement
if no return statement, python return None
def dummy():
print ('This is a dummy function, return no value')
dummy()#:> This is a dummy function, return no value
5.3.5 Return Multiple Value
Multiple value is returned as tuple. Use multiple assignment to assign to multiple variable
def minmax(x,y,z):
return min(x,y,z), max(x,y,z)
a,b = minmax(7,8,9) # multiple assignment
c = minmax(7,8,9) # tuple
print (a,b)#:> 7 9
print (c) #:> (7, 9)
5.3.6 Passing Function as Argument
You can pass a function name as an argument to a function
def myfun(x,y,f):
f(x,y)
myfun('hello',54,print)#:> hello 54
5.3.7 Arguments
args is a tuple
5.3.7.2 Example 2
First argument goes to x, remaining goes to args as tuple
def myfun(x,*args):
print (x)
print (args) #tuple
myfun(1,2,3,4,5,'abc')#:> 1
#:> (2, 3, 4, 5, 'abc')
5.3.7.3 Example 3
First argument goes to x, second argument goest to y, remaining goes to args
def myfun(x,y,*args):
print (x)
print (y)
print (args) #tuple
myfun(1,2,3)#:> 1
#:> 2
#:> (3,)
5.3.7.4 Example 4
def myfun(x,*args, y=9):
print (x)
print (y)
print (args) #tuple
myfun(1,2,3,4,5)#:> 1
#:> 9
#:> (2, 3, 4, 5)
5.3.8 keyword arguments
kwargs is a dictionary
