The Python Ecosystem

Input from Keyboard.

raw_input  :  All user input is assumed to be string 

input :  Input is automatically assigned a data type based on user input :  a= input (‘ Enter a number ‘)

Flow Control.

if .. elif .. else

for, while,  :  There is no do while 

break, continue,  :   break ( to come out of the loop ),  continue ( go to the beginning of the loop )

 pass  :   Skip or Empty statement, place holder for future code  ( similar to abstract in java )

else in loop :    Else is executed when the condition is exhausted, so incase of 

             if statement,  else will be executed when the list is iterated 

             while statement,  else will be executed when the condition turns false 

Range

Used to generate lists containing arithmetic 

range ( stop ),  range ( start, stop ), range ( start, stop, step )   —>   

where start default is 0, stop => stop -1   , step cannot be set to 0,  default of step is 10

 

Sequences  ( Lists, Tuples, Xrange, String )

List of values bound together in a container having the same datatype

Notes:  In python everything is an object… ( 1, “323”, int… )

Functions in sequences  

     Compare :  cmp()  … Example  cmp( list1, list2 )  … compares element by element,  returns -1 if element in list 2 is greater than element in list 1 

      Max  :   max()  , Min(),  List() , Tuple()

      Len :   len()

LIST  :    Container containing number of objects is a give order

        List is mutable unlike String which is immutable

       All objects are enclosed in square brackets and the sequence/index always starts from 0 representing the first element

       Allows you to add remove objects from the sequence 

       Different from array as it can contain heterogenous elements .   Example (  a = [ 1, 2.4, “test”]

       List can also have list in lists. Example (a = [ [ 1,2,2.4] , ‘2’, 2.4]

       Can use a negative index to retrieve elements from back , and slicing is also allowed Note (second parameter for slicing the the number of elements and not the position of the element )

       Invalid index reference will give an IndexError error

       Examples :    list = list() …  Empty List  ,   li =  list(range(4)) =>   [ 0, 1, 2 ,3 ]  ,   var a = ‘Test’  li = list(a)  = > [‘T’,’e’,’s’,’t’]

         a = len(list(range(5)))    ,     li[index] … for accessing ,   li [ start:stop] …. slicing,  print (li[-2]))

 

        NOTE :  When assigning a  list to another list you are create a POINTER and NOT A COPY

        Example :     l = [1,2,3]   a= l ,  a[1] = 6,   print(l) =>   [ 1,6,3 ]

        In order to copy another list instead of assigning use the following 

        a  = l.copy()

 

        MANUPLATION List Functions 

          list.append( value )  … add an element to the list

          list.extend (list of values )  …. add another list to existing list

          list.insert(index, value ) ….  insert an item in an list at the index position

          list.remove(value)    … will  remove only the first element of the value if duplicate exists

          list.pop() … will remove and return the last element on the list

 

         SEARCHING List functions 

          l.index(value)  ….  returns the index of the value being retrieved 

          Note :  Throws an exception if the value is not found when using index()

          l.in(value)  …. returns true or false 

 

        OPERATORS  List Functions

         +   :    Similar to exend()  where it concatenates 2 lists

                   You can also use to it as    L  += “R”

         *    :   Replicating the list number of times mentioned  :   l = l*3 

 

TUPLE 

  –    It is a IMMUTABLE list   ( Cannot be changed once created )

   –   Created similar to list except it is create in PARANTHESIS   and  NOT SQUARE BRACKETS

    –  Mostly used when the list IS NOT  to be manipulated 

    Example :     a  = (1, 2 )   …  note this list cannot be manipulated as it is a TUPLE

ENUMERATE

   –   Creates a generator object which supports the iteration protocol

    – Built in function that operates on sequences such as lists and tuples and returns  an enumerate ( index, value ) pair for each element in the list/tuple

    – Example :  l = [1, 2, 3]     l = list(enumerate(l)) ,  print(l) :   [ (0,1), (1,2), (2,3) ]

      for count, value in enumerate(values):   print(count, value)

DICTIONARIES

   –    Key Value Pairs   (  Elements are accessed by Keys )

   –    UN ORDERED   ( Only difference between Lists and Dictionaries is the that list are ORDERED

   –    Hash Table is created for all keys in Python  for SPEED  ( Similar to a index in Oracle table )

   –    Syntax :  Used Curly Braces with list of Key – Values separated by :

         Example  a = { 0 :  “Test”,  1 : “Test 2” }

    –    Embed an Dictionary within a dictionary or a Tuple

Accessing / Managing Dictionaries 

     –   Keys()  :   Function returns are the keys in the dictionary : 

           Example  l= { 193: ‘Test’, ‘AB’ : ‘ Test1″ }   =>  [  type(i) for i in l.keys()  ]=>     [ int, str]

                             l[0] = “Test2”   = >   Add the Value “Test2” with 0  as an index   ,  print(l) =>   [int. str, int]

     –   Values(), item(), get(), 

      –  update(Dict )   Used to merge to dictionaries .  Compares the keys, if found updates else adds 

          x.update({‘Age’: 40})     …  Adds an element if the key is not present

       – pop(Key)     Removes the item associated with the key from the dictionary

     –   If key is not present it will throw a KeyError exception

     –   cannot SLICE & Concatenate as it used keys and not indexes

     –  you can used  in and len() 

     –  Contains iterator functions and Next to handle iterations on dictionary items 

         Example  for key,value in  l.items():     print (key,, value )

SETS

  –  Niether mappings or Sequences

   – Tuples , Lists ..

   –  Un Ordered and Immutable

   –  Only Unique values , no duplicates allowed

       Example :    l = set(‘army’)     print(l)  =>  { ‘a’, ‘r’, ‘m’, ‘y’ }

Operations: 

     –  Union(),      Set1 | Set2 

      –  Intersection()   Set1   & Set2

       – Difference()   Set1 – Set2

 

FILES 

   –  Storage units managed by OS

    –  open() to create a file or open and existing file 

       Syntax :  fl = open( filename [, access mode ] )   ….  ‘w’ – write,  ‘r’ – read, ‘r+’ – read write’ ,  ‘rb’ – read binary

        Note :  ‘w’ will overwrite an existing file

Methods 

     read()   …  f.read() … Reads the file and moves the cursor to the eof 

     seek(position) ….   f.seek(0) …   Positions to the start of the file 

     closed(), mode(), name()   are attributes of the file

     write(), close()        

      tell()  –   Gives the position in the file 

      seek (offset, [from])  ….  from values  0(default) – beginning of file,  1 – current position , 2 – end of file

      rename(),      remove()

      mkdir(), chdir(), rmdir(), getcwd()