Search This Blog

Thursday 7 December 2017

Python Quick Reference - Notes

1.       Python Interactive command prompt is called REPL (Read-Eval-Print-Loop)
2.       Python uses indentation for identifying block of code
3.       To get help use help(modulename) like help(math)
4.       Python is strongly typed and dynamically typed object-oriented programming language
5.       Scalar or primitive types are
a.        Int
                                                               i.      Unlimited precision signed interger
                                                             ii.      By default specified as decimal value like 43
                                                           iii.      Can also be specified as either Binary (using 0b prefix like 0b10) or Octal(using 0o prefix like 0o10) or Hexa(using 0x prefix like 0x10)
b.        float
c.        bollean (true or false)
d.       None (null object)
6.       Type conversion can be done using type function like int(3.5) will result 3
7.       Special floating-point values “nan” not a number, “inf” infinity
8.       If expr:
     Block
Elif
     Block
9.       while expr:
           Block
10.   for a in b[]:
       Block
11.   break breaks entire loop and continue skips current iteration and continues with next iteration
12.   pass does nothing
13.   str (used as string type) is a immutable sequence of Unicode code points
14.   strings are used with quotes (either single or double)..
15.   “”” and “”” is used for multiline comments, also used for multiline strings when used with assignment
16.   # used for commenting lines
17.    THERE IS NO SPEPERATE TYPE FOR SINGLE CHARACTER.
18.   str type provide many string methods like capitalize, split etc
19.   list are mutable sequence of objects.. ex. [‘b’,’c’,’e’,’f’]
20.   dictionaries pair of key: values ex {“India”: “Delhi”, “USA”: “Washington dc”}
21.   two important idioms __name__ and __main__
a.       module is executed once when its first imported
b.       when module is imported using import command, __name__ will be equal to module name (or .py file name)
c.       when module is executed as script using “python modulename.py” then __name__ will be __main__ therefore if we want to execute the code only if module is called as script then put the code in if block with predicate as “__name” == “__main__”
22.   command line arguments
import sys
var=sys.argv[1]
sys.argv[0] is the module or script file name
23.   In python every thing is an object.. for example if a variable “int x=500” defined, “500” is stored in “int” object and “x” will have reference to “int” object.. i.e. if “x” is reassigned with different value then “500” object is not modified instead “x” reference will be changed to point to new object. In case of list objects, lists are mutable therefore same object gets modified
a.       Id() – function returns unique identifier for an object..ex: id(x)
b.       “is” – operator used to check equality of 2 objects.. i.e are both point to same reference?
c.       Python does really have variables.. its has only the named references to an object
d.       “dir()” function returns all the imported modules, functions and different type including special build in types.. for ex: dir(HelloWord) return all the HelloWord.py file components
e.       “type()” returns type of an object
24.   Lambda functions are simple one line functions
a.       For example “def resultd(x):
b.                                        return x*2
c.       Could be written as “resultd=lambda x: x*2”
25.   Collections
a.       “str”
                                                               i.      “abac ass dfsde”.split()=[“abac”, “ass“,“dfsde”]
                                                             ii.      “abc”+”cdf”=abccdf
                                                           iii.      “abc”*2=abcabc
                                                           iv.      Other functions including .. join, capitalize, format, partitioned etc .. refer help(str)
b.       “list” -- heterogeneous mutable sequence
                                                               i.      Elemenets are idexed from zero.. user subscript like list[index] to access specific element
                                                             ii.      Use slicing technique like list[1:2] to access range of elements
                                                           iii.      User -1,-2 ..  indexing to access from last element
                                                           iv.      List.index(“value”) will give element position in list
                                                             v.      “in” and “not in” can be used for membership test
                                                           vi.      “del list[4]” to delete an element by index and “list.remove(“value”) to remove element by its value
                                                          vii.      “list.append[“value”]” or “list.insert(idex ex.2,”value) for inserting values
                                                        viii.      “,“.join(list) will give a string with elements separated by comma
                                                            ix.      “list.sort(key=len)” will sort elements in list using length of element as key
                                                             x.      “list.reverse()” will reverse elements in list
                                                            xi.      sorted(list) will return list of sorted
                                                          xii.      reversed(list) will return iterable object with reversed list
c.       “dict” – unordered mapping from immutable keys and mutable values
                                                               i.      Keys must be unique in dictionary objects
                                                             ii.      If we want to interate only thorugh values then use dictname.values() iterable.. for items dictname.items(), for keys dictname.keys()
d.       “tuple” – heterogeneous immutable sequence
                                                               i.      Similar to list but elements can not be changed and enclosed in parenthesis
                                                             ii.      For single element tuple use trailing comma ex..(abc,)
                                                           iii.      Parenthesis for mini tuples may be omitted, this is useful unpacking references ex.. high-value, low-value=maxmin([1,4,6,7,8]) .. high-value=8, low-value=1.. maxmin is userdefined function
                                                           iv.      “in” and “not in” can be used for membership test
e.       “range”
                                                               i.      range(5) – will give 0,1,2,3,4
                                                             ii.      range(5,10) – will give 5,6,7,8,9
                                                           iii.      range(5,10,2) – will give 5,7,9
                                                           iv.      enumerate() yields (index,value) tuples.. use this instead of range(leg(j)) misuse of range
f.        “set” – unorderd unique mutable set
                                                               i.      “set()” creates empty set
                                                             ii.      Same as list with curley brackets {}
                                                           iii.      When list converted set, duplicates get deleted
                                                           iv.      Mainly userd for functions list “setname.issubset(setname)”, “setname.issuperset(setname)”, “setname.isdisjoint(setname)” etc
26.   Exception handling
a.       Try… Except..Finnaly
b.       Raise without parameter, it re-raises current exception being handled
c.       “except exception: “ is any other exception to handle
27.   Comprehensions
a.       List comprehension example
                                                               i.      Words=”why sometimes I have believed as many as six impossible things before breaskfast”.split()
                                                             ii.      [len(word) for word in word] is the comprehension to calculate all the words lengths and create new list type [3,9,1,4,8,2,4,2,3,10,6,6,9]
b.       List comprehension syntax is [expr(item) for item in iterable]
c.       Set comprehension is same as list comprehension but uses {}
d.       Dict comprehension is {keyexpr:value expr for item in dict}
28.   Iterator
a.       Itr(interable) to get iterator object
b.       List, set etc are iterable objects
c.       Iterator supports functions like next .. next(iterator) will give next element until end and at the end it throws exception StopIteration
29.   Generators
a.       Sequences are evaluated lazily i.e. it will calculate the next value only on demand
b.       All generators are iterators
c.       We can create generators using “yield” in modules instead of return
d.       Generator supports functions like next .. next(generators) will execute statements in module until next yield statement and keeps track of status. At the end  it throws exception StopIteration
e.       Generator comprehension can be created similar to list comprehension but use () instead of []
30.   Standard libraries
a.       “sys”
                                                               i.      For stderr, stdout, stdin, argv
b.       “pprint” pretty print (from pprint import pprint as pp)
c.       “os” import os
                                                               i.      os.path.realpath(p) for file path, os.stat(p).st_size for file size
d.       “glob” import glob
                                                               i.      glob.glob(“*.py”) for searching for all python files
e.        “math”  from math import sqrt .. similarly all math functions
f.        “inertools” from intertools import islice, count
                                                               i.      Islice provides lazy slicing functionality
                                                             ii.      Count() open ended range.. I,e end less range
                                                           iii.      If we need to read all first 1000 primes we can use something like islice(all_primes,1000)… islice((x for x in count() if is_prime(x)),1000)
                                                           iv.      “any” , “all” itertools are similar to logical operators AND and OR but works on interable series and returns bool type true or false
                                                             v.      “zip” combines 2 or more pairs of sequences into matching pair tuples a= [1,2] and b=[a,b] then zip(a,b)=[(1,a),(2,b)].. zip can accept more then 2 interables as input
31.   Classes
a.       “class classname:” for defining a class
b.       “self” first argument to all instant methods in class
c.       Instance methods are functions which can be called on objects
d.       __init__ () is initialization method similar to constructors in Java but not same
e.       There are no access modifiers, everything is public type
f.        Inheritance or extend can be achieved by suppling parent class as parameter to class like “class classname(parentclass):”
g.       Overloading is achieved using duck type not really with different parameters like java
h.       Class variables can be defined outside all functions/methods in a class.. these class variables will be same for all class instances.. this is similar to static variables in Java
i.         “super.” Can be used similar to “self.” But to refer parent class object in the child(or inherited) class
32.   File management
a.       F=Open()
                                                               i.      Input parameters are “file name”,”mode”,”encoding”
                                                             ii.      Mode default is read and text mode
                                                           iii.      Encode default is  UTF-8
                                                           iv.      Open(“file.txt”,”rb”) opens file in read mode and binary mode
                                                             v.      R-read, w-write, a-append, x-exclusive to create new file and fail if file already present
b.       f.write()
                                                               i.      writes stream of data , does not automatically create new lines.. must supply exclusive \n characters
                                                             ii.      file contents are visible only after f.close()
c.       f.read()
                                                               i.      f.read(4) reads 4 bytes
                                                             ii.      accepts number of characters to read and pointer moves to next non-read characters
                                                           iii.      at the end of the file read() returns empty string
d.       f.seek()
                                                               i.      rewind the file position with seek
                                                             ii.      accepts number of position to place the point back in opened file
e.       f.readline() reads a line at a time
f.        f.writeline() writes a line at a time
g.       f.writelines() writes multiple lines at a time
h.       f.close() – closes file
33.   context managers
a.       “with” provides the context management.. i.e. even if we do not close the file explicitly, “with” closes the file at the end of context
b.       with  open(“test.txt”,”w”) as ff
c.       context manager protocol ... from contextLin import closing..
1.       closing(fucntionname whre close needs to be automatically hanled)
34.   UnitTest
a.       Automated and repeatable tests
b.       Key concepts
                                                               i.      TestCase – basic unit of test organization in unittest
                                                             ii.      Fixtures – are features of code that run before and/or after test function
                                                           iii.      Assertions – specific tests for test cases to determine pass or fail ex: is_decimal():
c.       Fixtures avaiables
                                                               i.      “def setUp(self):” is test cases method available to run code before test functions
                                                             ii.      “def tearDown(self):” is test cases method available to run code after test functions
d.       Test functions are defined as testcase mentod with name starting with “test_” ex: “def test_file_present(self):”
35.   PDB – Python DeBugger
a.       This is REPL debugger
b.       “import pdb” then use pdb.set_trace() to start debugger from middle of code
c.       Type help to list all pdb commands
d.       To run a script in debugger mode use “python -m pdb scriptname.py”
e.       In pycharm IDE, we can just put breakpoint and run then step into or step over to do debugging
36.   Virtual environments
a.       Virtual environment is a light weight , self-contained python installation user can create without admin privileges on system
b.       “venv” or “virtualenv” are tools we can use to create virtual environment. “venv” is shipped with python3 if not we can install virtualenv from web
c.       To create new virtual environment simply run “venv” as script as “python -m venv venv-name”  (venv-name is virtual environment directory name)
d.       Once created we can run active scripts from ./bin directory (on linux source it and in window just run it)
e.       Use “deactive” to leave from virtual environment
37.   Packaging and distribution
a.       Using standard “distutils” module
                                                               i.      Create steup.py as
1.       “from distutils.core import setup”
2.       setup(
3.                  name=’packagename’
4.                  version=1.0
5.                  py_modules=[all py modules without .py]
6.                 Any other meta data like author , description etc
7.                  )
8.       Once setup.py created, it can be installed in virtual environment using “python setup.py install”
9.       We can use setup.py to create different formats of distributions for example “python setup.py sdist --format zip” will create zip file for distribution
b.       Use “pip” for thirdparty packages installation. This is similar to “apt-get”,”zipper”,”yum” in linux distributions
c.       We can use “pyinstaller” to create binaries like .exe installable files.. these can be run on any computer without python being installed
d.       To create a set up wizard, we can install tools like “inno setup”

No comments:

Post a Comment