Looking for a Tutor Near You?

Post Learning Requirement »
x

Choose Country Code

x

Direction

x

Ask a Question

x

x
x
x
Hire a Tutor

Python Training Notes

Loading...

Published in: Python Programming
3,559 Views

My notes while I conducted a training session on Python to my students in May,2017. Hope this will be benefecial and equally liked by others.

S B / Howrah

14 years of teaching experience

Qualification: B.Tech/B.E. (IIEST (Formerly BESU, Shibpur) - 2009)

Teaches: Algebra, IT & Computer Subjects, Mathematics, Statistics, Bank PO, IBPS, SSC Exams, WBCS, Data Structures, DBMS & RDBMS, PL/SQL, IIT JEE Advanced, IIT JEE Mains, WBJEE, Electrical, Electronics, IT, C / C++, Java And J2EE, Python Programming, Shell Scripting

Contact this Tutor
  1. Python Notes: Python is a high-level, object-oriented, language. Striking features: interpreted, extendable programming No braces { } . Instead (for loops/ condition checking) we use No usage of semicolon as statement terminators. INDENTATION is of great importance. Enriched with numerous modules. Comma(,) is used for concatenation. Plus is also used for concatenation. Comment using the symbol # 30 keywords in Python. Version 3. * ensures that we use print with parentheses and this is not backward- compatible . Loosely typed language. So no declaration of variables and its corresponding datatype. Variables : Numbers String Tuple List Dictionary Numbers : Int Long Float Complex Immutable array of elements. Tuples are always enclosed within ( ) Mutable array of elements. Lists are enclosed within [ ] Key-value pair. Dictionaries are enclosed within { } -2A15 -2A31 2A15-1 2A31-1 fl no - 12e-1 (mantissa e exponent) hex no @x12AB large hex no - @xFFFFFL Deleting a variable: del There are two mathematical constants: math. pi math. e x=3.7 Typecasting functions: int (x) long(x) float (x) 3.7 + complex (x) Decimal->Binary: bin() Decimal->Octa1: oct() Other mathematical functions: ceil (x) floor() min(xl x2 x3 max(x1,x2 x3 sin cos tan sqrt(x) pow(x, y) log() asin acos atan
  2. exp ( ) Operators: 1. 2. 3. 4. 5. Arithmetic Operators Comparison Operators Assignment Operators Logical Operators Bitwise Operators and or not (!) I (OR) [Shifting a number to the left by n bits // (Floor Division) ** (Exponent) >> vmax 12 Looping : - a if a>b else b Initialization block while() . block of statements Increment block 'PERL'] langs ' Scala ' for i in range(3): print langs[i] Character and ASCII Code>) Mutual conversion -> get corresponding charcter -> Corresponding ASCII value ord( '') Tuples :
  3. weekdays ('Mon' Tue' weekdays Tuesday ' Wed 'Thu' Fri' 'Sat') 2 functions associated with tuple: weekdays . index( ' Fri' ) weekdays. count( 'Mon') Length of tuple: len(weekdays) List: fruits Length: Append : - ['Mango' len append ' Apple' pear S' 'Guava'] Inserting at arbitrary position: insert (index, ) Popping out the last inserted element: pop() sort (list name) Sort a list or del (list [index]) Remove a specific element: remove(value) Reverse a list: reverse() Repetition [ : ] Slicing Operator [:] Slices from the index having the start position to the element having index (end position-I) Elements in a list are also index from backwards as -1, -2, -3 Additional functions: len(), min(),max() Tuple->List : wdl = list (weekdays) wd]. insert (O, 'Sun') tuple(wdl) weekdays del wdl Concatenating lists: list3 - listl + list2 Dictionary : 'K2':'V2' myDict {'KI':'VI' & so on Note: If a dictionary has multiple values corresponding to the same key then the last assigment wins. Length: len(myDict) Set of all keys: myDict. keys() Checking existence of a key: myDict . has key() Delete a particular key-value pair: del myDict[ ''] Delete entire dictionary: del myDict Updating a dictionary based on another dictionary: . update() Convert two lists into a dictionary. Two Lists -> List having pairwise tuples 11 12=11, 4, 9] -> Dictionary
  4. 13 zip(11,12) - dict (13) squares Declare a matrix of pre-defined dimension of m*n in a single line: myMatrix myMatrix Strings: = [ for x in range(5)] for y in range(3)] 0], A string can be enclosed within single, speech "The PM said, folder "C : \\newfolder " double or triple quotes. The solution to inadvertently face any escape sequence problem is i) carefully prefix each escape sequence with a \ i i) Declare the sring as a raw string. e.g.: myDir The usage of is to preserve the escape sequences(characters) while entering a strings. It stores the string verbatim. Escape Characters: \b Repetition [ : ] Slicing Raw string in/ not in Membership word[l:] Prints from indexl(2nd character) to the last word[:-2] Prints from the beginning to the last but two characters. word[-3:] Prints from the last but two characters to the last word[: : 2] Prints alternate letters starting from the beginning. Specifiers : Format Yod Yos 0/6c %u print ("Mobile Number = %14s Bill = print 'Mobile Number = %14s Bill = String manipulation functions: Rs. Rs. bill) 0/6-10 bill) [Python] find(substr I character, [start, [end]] ) index(substr I character, [start, [end]] ) error. Returns -1 if there is no match Throws an exception if there is no join Joins a list to form a string based on the delimiter. . join
  5. split Splits a string into a list based on the delimiter. strip Gets rid off unwanted characters on either end. count (substr I character, [start, [end]] ) Counts the number of occurrances of a particuar character/ substring. startsWith() endsWith() capitalize( ) lower ( ) upper() is Title( ) isAINum( ) isDigit # Implement a telephone directory[Bub1e Sort of Strings] Functions : def () . [return ] Add two integers: def sum(a,b): — a-I-b s return s print "Sum = Note: We have to first define the function before using it. Passing a default value to a function arg: def sum(a, — a-I-b s return s Python supports arguments of variable length. def myFunction(first, *rest) return rest myFunction( [1, 2, 3, 4, 5] ) Implement a summing mechanism of arbitrary number of numbers. Recursion : Factorial, Fibonacci, def (n): if : return 1 Sum of Natural Numbers, Tower of Hanoi, etc. return n+fn()
  6. Command Line Arguments(CLA) . import sys python cdr .py 8697731112 12 len(sys.argv) sys.argv[l] # Access the first argument passed (Not the script name) Object Oriented Programming: class : def init (self, varl, var2) : self . varl = varl self .var2 = var2 qwerty" var3 def funcl(self) . print self. varl + Instantiating an object of a class: al = Inheritance: class (A) . # Demoing Method overriding def funcl(self) . super (B, self) . funcl() CHECK print "Indigenous of the child. " Array of Objects: 5 objects of the Rectangle class = [Rectangle() for i in range(5)] Random class: import random random . random( ) Prints values within [O, ) random . uniform(a, b) Prints values within a and b random. randrange(a, b, step) Prints integral values between a and b which are at step deviations from a random . random . : File Manipulation: Reading from Writing to Appending to Modes of operation: Picks up a random value from the list Shuffles a list Read ( r) Write(w) Append(a) rb+ wb+ [Default mode: r] wb ab W+ Opening a file: fp open( "myFi1e . txt " , open(file name, [access mode, [buffering]] )
  7. Buffering No buffering Line buffering 1 number (>1): The positive number is the size of your buffer number System default buffer size. Alternatively, with open( "ArrayOfObjects. py" "r") as fo: - fo.read() cont Reading a file line by line: with open( "ArrayOfObjects. py" "r") as f p: for line in f p: print i,' line Reading a specific number of characters: f p. read( ) Closing a file: fp . close() Functions associated with file: read() write() tell() Provides you the position of the current file pointer seek() Change the current position of the file pointer. seek(threshold[, from where]) from where: From the beginning of the file (default) From the current file pointer 1 End of file. 2 Writing to a file: [Mode of operation should be w or equivalent ] Appending to a file: fp . The OS module: import os [Mode of operation should be a or equivalent] Know current working directory: os.getcwd() List all files in the current dir os.list(' Create a dir: Change Dir: Remove Dir: os.mkdir( ) os.chdir() os. rmdir() Removing a file: os . remove() Check existence of a path: os.path.exists( '') Is the object a file/ directory: os.path.isfi1e() os . path . Rename files: os. rename(, ) The shut il module(A1ternative module of os) shut il . rmtree( ) # Delete all subdirectories irrespective of they containing
  8. files or not. Size of a file: os . path . getsize() OR os.stat() . st size # List all . py files in current directory import os for j in os.listdir(' if os.path.isfile(j) and j.endswith(' . txt'). print 1 The glob module: import glob Search for a specific type of file in the current directory: glob. glob( '*txt') Search for a specific type of file in all the subdirectories: glob . •P)/' ) Exception : try: except : finally: Defining custom Exceptions: class def def try: MyCustomException(Exception) . init (self , message) . self . parameter = message (self): str return self. paramater if raise MyCustomException, "Low balance" except MyCustomException, ErrMsg: print ErrMsg Defining custom modules: . py #Variab1es b #Functions
  9. cursor execute fetchall # Connect to Mysql instance import MySQLdb myDb MySQLdb . connect( ' mycursor = myDb.cursor() #C1asses C . py import MyModu1e MyModu1e. f (12) Database Connectivity. Generic ODBC module: pyodbc Mysql: MySQLdb Postgres: psycopg2 Mysql connectivity. connect(, , ) password= ' postgres root ' name ' SauravMysq11 ! personal ' ) vname query result raw input( 'Enter: " select * from m user where mycursor . execute(query) rows = mycursor . fetchall() print rows myDb . close() Postgres Connectivity: import psycopg2 psycopg2 . connect ( "dbname= ' saurav ' con - con.cursor() mycursor ' select * from python trng' query mycursor . execute(query) result = mycursor . fetchall() print result Functional Programming: map (aFunction, asequence) filter (aFunction, asequence) reduce(aFunction, asequence) user= ' postgres ' # Sum of natural nos, Factorial, Cumulative addition/ subtraction/multiplication/div Squaring all the numbers from 1 to 10: map(lambda x: x* *2, range(l, 11)) Getting only the positive elements from a list: filter (lambda range( -10, 11)) Square all odd numbers from 1 to 50 based on an input of [O,
  10. map(lambda y: y* y, filter (lambda x:x%2@ and range(l@l))) Sum of all natural nos from 1 to 10 >>> reduce(lambda range(ll)) 55 Factorial of 4 >>> reduce(lambda x,y:x*y, range(1,5)) 24 Find the largest element in a list reduce(lambda x, y: x if else y Debugging in Python: import pdb pdb.set trace() Execute the current command n , -1, 99, 87, 96, 78, 75, 1 Show me the position of the debugger within the code p : Displays the variable q c s Quit the debugger Turn off the pdb prompt and continue Step into a function Return to the return statement of the current function. Pressing Enter will execute the last command. Unit Testing in Python: Using doctest and unit test modules doctest # Using doctest import doctest def fibo(n). fibo(l@) 55 fibo(15) 610 >>> fibo(2@) 6765 >>> fibo(3@) >>> for i in range(n): — b, a-I-b if return a name main doctest . testmod()
  11. N/A