Functions
– First class citizens ( Pass functions as parameters, returned as parameters, nested functions similar to objects ). To be treated as any other variables.
– Standard Libraries ( default libraries provided as part of base install )
Syntax : def function_name ( arguments):
Pass by Object Reference : Python supports call by value ( where value is object reference, not the value of object ). Hence it is also called Pass by Object Reference
Note : Arguments when passed behave different when depending on the operation performed on it
z.append(b) will impact the original object and behaves as pass by reference
z = z +b will not impact the original object as it creates a copy in this case because of the assignment operator
z = z will behave as pass by reference only
Scope of Variables :
– LEGB ( LOCAL, ENCLOSED, GLOBAL, BUILTIN )
– Named parameters : Passing parameters ( a, c = 10 )
Note: Positional parameters cannot be passed after the named parameters
– Unknown number of parameters (Arbitrary Argument List ) :
*args – pass a list as arguments
def concat(**args): return ” ” .join(args)
**args – pass a dictionary for named arguments parameters
def name_params(**kargs): for k,v in kargs.items():
– Function returning a function
Example : Linear Equation y = mx + c
def lineart_eq ( slope, c = 0 ): def equation (x) : return slope*x +c
Calling it : eq = linear_eq (3, 5 ) returns a equation function, Invoke returned function : eq (10)
Exceptions & Error Handling ( Catch and/or Raise )
Errors : : IOError ( input/out), ImportError ( module cannot be found ), ValueError( Incorrect value returned by argument)
Syntax :” Try : Except ‘ErrorName’: Else :
Note: Make sure Else block is executed prior to the finally block
sys.exit(ErrorCode) : Exits the program returning the error code, a error code of 0 or null means program completed successful and error did not occur or error was handled.
Finally: Use of finally to clean up resources and it always gets executed, irrespective of exception or not
Assert : Used for debugging, raises an exception when condition is not met
Syntax – assert ( test , message )
The error raised is the AssertionError. There is a standard hierarchy of exception BaseException sits on top of this
Standard Library and functions
Import : import sys – Used to import a standard library
sorted() : sorts a lists , tuples
Note a.sort() will re-order the list a , while sorted(a) will return a sorted list without changing a
Example: sorted( a, reverese=True) , a.sort(reverse=True)
Example: demographic = [ ( ‘John’, 6, 34 ), (‘Amy’, 7, 20), (‘John’,6, 32 ), (‘Han’, 7, 12)]
Use the itemgetter() function to specify the index of the item used to sort the list
from operator import itemgetter
sorted (demographic, key = itemgetter(1, 2))
Out[19]: [(‘John’, 6, 32), (‘John’, 6, 34), (‘Han’, 7, 12), (‘Amy’, 7, 20)]
sorted (demographic, key = itemgetter(1))
Out[20]: [(‘John’, 6, 34), (‘John’, 6, 32), (‘Amy’, 7, 20), (‘Han’, 7, 12)]
abs() :
basestring() :
all() :
any() :
bin() :
bool() :
enumerate() :
eval() :
dir(): used to returns the objects attributes such as methods and constants along with the name of the object
LAMBDA FUNCTIONS
- One line function ( concise and easy to read and write ), cannot contain more than one function
- Anonymous lambda functions defined by keyword lambda
- Can contain any number of arguments
- Example add = lambda x , y : x + y – add(3,4) => 7 Note : x & y are input parameters
- Example power = lambda x : lambda y: x ** y – power(3)(4) => 81 or d= power(3) , d(4) = > 81
MODULES
Any .py file is called a python module . Used to save to a python file
import module_name Example : import hello ( where hello.py is the file name to be imported )
One can import a module file written in other languages such as C and C++
A module can have definition of variables, functions and classes
The first time python module is loaded, it goes through an initialization phase. It automatically creates a namespace and store the definition of the functions, variables and classes, runs the code in the module
Reference the function or variable using the namespace Example hello.print_hello()
you can Import only the function from a module using the from … Sytax: from module_name import function_name
you can also give an alias name to the module using as … Sytax : import module
SYS module : Used for controlling and interacting with the python interpreter.
sys.exit(), sys.argv, sys.input()
OS & SUBPROCESS Module: OS related
OS module mainly used for paths, permissions and file operations
os.getcwd(), os.mkdir(), os.mkdirs(), os.chdir(),
os.path().? .join(), .abspath(), .normpath(), .split() ( returns file and dir separately ), .isdir() , .exists()
Subprocess module lets you interact with the OS to run commands and give info about the operating system.
subprocess.call() Example subprocess.call(‘ls’,1 ) …. runs the command and waits for the return code
MATH Module : Number-theoretic, ceil (next integer), fabs ( absolute number), copysign (10.00, -0.0 ) => -10.00
Power and Logarithmic functions, Trigonometric , Angular Conversions, Hyperbolic Functions, Special Functions & Constants
Note: Module does not handle complex numbers use CMath
RANDOM Module : pseudo random number generators for various distribution
random.sample(range(1000), 100 ) will return 100 random samples from a list of 1000 …. NO DUPLICATES
random.randrange(stop) randrange( start, stop, step ) => returns integer
DATETIME & TIME MODULE :
Computers generally store number from seconds passed from a specified date ( called EPOCH 12AM JANUARY 1, 1970 )
datetime() timedelta()
datetime.datetime.today() datetime.datetime(1920, 02,12, 5)
ZIPFILE Module :
Module to create , read, write, append and list a ZIP file
import zipfile , x = zipfile.ZipFile(“New Zip file name”,”w”) . x.write(“FileName1”) x.write(“FileName2) x.close()
x.namelist()
PACKAGES : Package contains multiple module.
Steps … 1. Download tar/zip file of the package, 2. Unpackage the module file/directory 3. It will have a setup.py file or README/txt file. 4. Execute : python setup.py install