Wednesday, March 5, 2014

Python IDE examples

Python:

-          We speak of software in terms of vertical applications versus horizontal applications.

-          Horizontal applications:
-          Not specific to given industry or line of work.
-          It includes word processors, spreadsheets etc.

-          Vertical application:
-          Industry specific.
-          Inventory system for automobile parts wholesaler, sales order system for a manufacturer and premium billing system.
-          We also have development software. Python and other programming languages fall in this category.

-          With these languages we create source code solutions for both vertical and horizontal applications.

Two requirements of computer program:
-          Data on which it will operate
-          Behavior for performing operations on that data.
-          Behavior(collection of instructions) is often called algorithm.
-          Program = Data+Algorithms
-          Three fundamental behaviors associated with any computer programming:
-          Sequence: series of instructions with no decision logic.
-          Iteration: loop with some kind of logic to terminate loop
-          Selection: controlled by TRUE or FALSE condition
-          Recursion:
-          We can create functions to do very complicated mathematical formula, compute interest on bank account, or regulate the cruise control on an automobile.
-          Point is that a program, in any language is developed by creating many small functions and putting them together in larger set of functions, modules, classes or procedures.

-          Sequence:

-          Instructions simply proceed from one to another without any decision making:
-          Def sequenceExample(x,y,z):
-          Temp = x;
-          X = z;
-          Z = y;
-          Y = temp;
-          Print(x,y,z)

Datatype:
-          C,C++,C#,Java:
-          Int x;
-          Float q,r,s;
-          X,r,q,s are all instances of integer and float data type.
-          Think of data type as cookie cutter from which you stamp multiple cookies
-          Int is cookie cutter.
-          X,q,r and s are the cookies.

-          The environment integrated into Python is called IDLE.
-          IDLE is integrated development environment for Python.
-          Using IDLE will make your early experience with Python more productive.

Advantages of Python:
-          Easy to read: much more clearly defined and visible to the eyes.
-          Easy to maintain: source code is easy to maintain.
-          Broad standard library: Pythons greatest strength is the bulk of library is very portable and cross platform compatible on UNIX, Windows and Macintosh.
-          Interactive mode: You can enter results from terminal right to the language, allowing interactive testing and debugging of snippets of code.
-          Extendable
-          Database: Provides interfaces to all major commercial databases.
-          GUI programming: Python supports GUI applications that can be created and ported to many system calls, libraries and windows system.
-          Scalable: provides better structure and support for large programs than shell scripting.
-          Portability across different OS except Apple Ipod, iPad series.
-          Python version used is 3.0, 3.2 and higher.
-          IDLE makes Python easy to get started.
-          IDLE allows you to open the development window in which you can create your programs.
-          You can save this window each time you write program in it.
-          IDLE command window has three angle brackets shown as >>>.
-          You will enter python commands at this prompt.
-          Python built in editor is called IDLE.
-          IDLE allows you to open window for composing programs.
-          >>> print("Hello Student") ## print string be sure to include parenthesis
-          Hello Student
-          >>> 42
-          42
-          >>> 42+5
-          47
-          >>> 42/3
-          14.0
-          >>> 42//3   ##divide one number by another truncated to integer with //
-          14
-          >>> 42^12
-          38
-          >>> 42 or 12
-          42
-          >>> 42 and 12
-          12
-          >>> x=[56,67,12,96,34]
-          >>> 
-          >>> data=input("Enter:")  ## variable named data
-          Enter:hello
-          >>> data          ## key in the data name
-          'hello'
-          >>> data = int(input("Enter:"))   ## convert input to an integer
-          Enter:45
-          >>> data
-          45
-          >>> fdata = float(input("Enter value:")) ##input using float conversion
-          Enter value:32.5
-          >>> fdata
-          32.5
-          >>> fdata = float(input("Enter value:")) ## input function, again
-          Enter value:67
-          >>> fdata
-          67.0
-          >>> print("line 1 \n","line 2 \n", "line 3 \n", "all done")
-          line 1
-           line 2
-           line 3
-           all done

-          Python list:

-          Is a collection type. Collection type is one that contains more than one value,
-          Sometimes all of the same type, sometimes of different types.
-          Python list is mutable, and can contain data of more than one data type
-          Being mutable means you can change values in list, remove items and add items.
-          >>> alist = ['howdy',67,'qwerty','*indalated', 66, 'SANDMAN']
-          >>> alist  ## enter list name and press the return/enter key
-          ['howdy', 67, 'qwerty', '*indalated', 66, 'SANDMAN']
-          >>> list = [325,345,3342,123123]
-          >>> list
-          [325, 345, 3342, 123123]
-          >>> List1 = [alist,list]
-          >>> List1
-          [['howdy', 67, 'qwerty', '*indalated', 66, 'SANDMAN'], [325, 345, 3342, 123123]]
-          >>> 
-          >>> breakfast = ["ham","cheese","oatmeals"]
-          >>> breakfast  #display entire list
-          ['ham', 'cheese', 'oatmeals']
-          >>> breakfast[2]   #get third item in the list
-          'oatmeals'
-          >>> breakfast[-1]  #get last item in list
-          'oatmeals'
-          >>> breakfast[0]  #get first item in list
-          'ham'
-          >>> breakfast[3]
-          Traceback (most recent call last):
-            File "<pyshell#52>", line 1, in <module>
-              breakfast[3]
-          IndexError: list index out of range
-          >>> breakfast{1}
-          SyntaxError: invalid syntax
-          >>> breakfast[1]  #get first item in list
-          'cheese'
-          >>> 
-          >>> breakfast.append("toast") ## add another item to list
-          >>> breakfast
-          ['ham', 'cheese', 'oatmeals', 'toast']
-          >>> breakfast[3] = "grapefruit juice"  #change orange juice
-          >>> breakfast
-          ['ham', 'cheese', 'oatmeals', 'grapefruit juice']
-          >>> menu = ['hot dog', 'hamburger', 'french fries', 'apple pie']
-          >>> for i in menu:     #create for loop over menu
-                          print(i)   ##print each item in list
-           
-                         
-          hot dog
-          hamburger
-          french fries
-          apple pie
-         >>> for index in range(len(menu)):
-                          print (index)
-                                   
-          0
-          1
-          2
-          3
-          >>> ordered_menu_list = sorted(menu)
-          >>> for menu in ordered_menu_list:
-                          print(menu)
-                                    
-          apple pie
-          french fries
-          hamburger
-          hot dog

-          Store list in external file:

-          You can store values from list in file using following function.
-          Note how we use print command for this implementation:
-          >>>def createCS3902File(filename, the_list): ##  create a function
-          f = open (filename "w") ##  open (create) a file named f
-          for i in the_list: ##  traverse the list
-          print (f, i) ##  put each item in the file
-          The file name can include a directory name for the computer.
-          In most cases, you want to put file in specific directory.

-          Nested Lists – also called Matrices

-          A list can contain other lists. This allows for matrix operations and
-          Other more complex structures.
-          >>> nested=[['q','w','e'],['a','f','r'],['x','y','z']]  ## two dimensional matrix representing row and column
-          >>> for data in nested:
-                          print (data)
-           
-                         
-          ['q', 'w', 'e']
-          ['a', 'f', 'r']
-          ['x', 'y', 'z']
-          >>> nested[1]
-          ['a', 'f', 'r']
-          >>> nested[2]
-          ['x', 'y', 'z']
-          >>> nested[0]
-          ['q', 'w', 'e']
-          >>> nested[-1]
-          ['x', 'y', 'z']
-          >>> nested[-2]
-          ['a', 'f', 'r']
-          >>> nested[-3]
-          ['q', 'w', 'e']
-          >>> nested[-4]
-          Traceback (most recent call last):
-            File "<pyshell#99>", line 1, in <module>
-              nested[-4]
-          IndexError: list index out of range
-          >>> nested[0][0]
-          'q'
-          >>> nested[0][3]
-          Traceback (most recent call last):
-            File "<pyshell#102>", line 1, in <module>
-              nested[0][3]
-          IndexError: list index out of range
-          >>> nested[0][-1]
-          'e'
-          >>> def area(height, width):
-                          return height*width
-           
-          >>> area(3,4)
-          12
-          >>> def cubeSurface(sideLength):
-                          return sideLength*sideLength*6
-           
-          >>> cubeSurface(3)
-          54
-          >>> def trapezoidArea(longbase, shortbase, height):
-                          return .5*(longbase + shortbase) *height
-           
-          >>> trapezoidArea(4,5,2)
-          9.0
-        
             Python dictionary type:

-          In dictionary, we can group information by name
-          It is defined with curly braces instead of square brackets.
-          >>> simpleDict = {1:"Open", 2:"Close", 3:"Ajar"}
-          >>> simpleDict[2]
-          'Close'
-          >>> simpleDict[4]
-          Traceback (most recent call last):
-            File "<pyshell#131>", line 1, in <module>
-              simpleDict[4]
-          KeyError: 4
-          >>> simpleDict[1]
-          'Open'
-          >>> simpleDict[3]
-          'Ajar' 

-          Python Strings:

-          The list and dictionary data types we studied so far are mutable.
-          That is, they can be added to , have data items inserted or removed.
-          Strings are immutable. They cannot be changed once they are created.
-          String uses parenthesis.
-          >>> s1 = ("Now it the time to group well")
-          >>> len(s1)
-          29
-          >>> x = sorted(s1)
-          >>> s
-          Traceback (most recent call last):
-            File "<pyshell#138>", line 1, in <module>
-              s
-          NameError: name 's' is not defined
-          >>> x
-          [' ', ' ', ' ', ' ', ' ', ' ', 'N', 'e', 'e', 'e', 'g', 'h', 'i', 'i', 'l', 'l', 'm', 'o', 'o', 'o', 'p', 'r', 't', 't', 't', 't', 'u', 'w', 'w']
-          >>> s1[0]
-          'N'
-          >>> s1[4]
-          'i'
-          >>> if 'all' in s1:
-                          print ('OK')
-           
-                         
-          >>> OK
-          Traceback (most recent call last):
-            File "<pyshell#145>", line 1, in <module>
-              OK
-          NameError: name 'OK' is not defined
-          >>> if 'it' in s1:
-                          print('OK')
-           
-                         
-          OK
-         >>> str1 = ("How now brown cow")
-          >>> str2 = ("The quick brown fox jumped over lazy dog")
-          >>> print(str1[3:6] + str1[13:17])
-           no cow
-         >>> print(str1[3:6] + str1[-4:]) ##catenate 3:6 with last four characters
-           no cow
-          >>> print(str1[::-1])
-          woc nworb won woH

-          Working with sets:

-          Set is defined with curly braces, set is not a list, it is its own unique data type.
-          >>> l1={'sdf','qaz','redf','ers','rfa'} # create a set
-          >>> l1
-          {'qaz', 'rfa', 'redf', 'ers', 'sdf'}
-          >>> for i in l1:
-                          print(i)
-           
-                         
-          qaz
-          rfa
-          redf
-          ers
-          sdf
-        
             Python functions:


-          Mathematical function is defined as y=f(x) where y is a value returned after the function
-          Performs computation on parameter named x.
-          Function may have more than one parameter as in y = f(a,b,c) where it performs operation involving those three parameters and returns a result in y.
-          >>> def f(x) :
-                          return x+1
-           
-          >>> y=f(24)
-          >>> y
-          25
-          >>> def f1(a,b,c):
-                          return(a+b)/c
-           
-          >>> y=f1(12,3,6)
-          >>> y
-          2.5
-        
        Nested functions:


-          def outer(a, b):
-          temp = 0
-          print ("initializing outer ")
-          def inner(x, y): ## a nested function
-          print ("Executing inner ")
-          return x + y
-          print ("executing call to inner from outer ")
-          temp = inner(x = a, y = b) ## call inner from outer
-          print ("now we return the result of inner ")
-          return temp
-          >>> n1= 42
-          >>> n2=bin(n1)
-          >>> n2
-          '0b101010'
-          >>> n3=hex(n1)
-          >>> n3
-          '0x2a'
-          >>> n4=int(n2,2)
-          >>> n4
-          42
-          >>> 234/5
-          46.8
-          >>> 234//5
-          46
-          >>> 234%5
-          4
-          >>> divmod(234,5)
-          (46, 4)
-        
-         
-          Assumptions for pre and post conditions:

-          It is often useful to put constraints on the values being computed in a function.
-          Python has several ways of doing this. Assertions are easiest approach.
-          >>> def compute_1(a,b):
-                          assert a<=9
-                          assert b<=9
-                          return a*b
-           
-          >>> compute_1(6,2)
-          12
-          >>> compute_1(12,1)
-          Traceback (most recent call last):
-            File "<pyshell#236>", line 1, in <module>
-              compute_1(12,1)
-            File "<pyshell#232>", line 2, in compute_1
-              assert a<=9
-          AssertionError
-       >>> def compute_1(a,b):
-                          assert a<=9, "precondition error"
-                          assert b<=9, "precondition error on b"
-                          return a*b

-           AssertionError: precondition error on b

-          >>> compute_1(8,12)
-          Traceback (most recent call last):
-            File "<pyshell#240>", line 1, in <module>
-              compute_1(8,12)
-            File "<pyshell#239>", line 3, in compute_1
-              assert b<=9, "precondition error on b"
-         
       
-          >>> s=lambda x:"" if x==1 else "s"
-          >>> s(3)
-          's'
-          >>> s(1)
-          ''
-          >>> f1=lambda x:(x*(x+1))/2  #compute sum of 1 to x
-          >>> f1(5)
-          15.0
-          >>> f2=lambda x, f:f(x) ##apply function to x
-          >>> def squareIt(v):    ##sample function
-                          return v*v
-           
-          >>> f2(5,squareIt) ##apply the squareIt function
-          25
-          >>> h = lambda a, b: math.sqrt(a**2 + b**2) ## Pythagoras formula
-          >>> h(3,4)
-          Traceback (most recent call last):
-            File "<pyshell#254>", line 1, in <module>
-              h(3,4)
-            File "<pyshell#253>", line 1, in <lambda>
-              h = lambda a, b: math.sqrt(a**2 + b**2) ## Pythagoras formula
-          NameError: global name 'math' is not defined

-          Recursion:

-          Function calling itself over and over again.
-          Recursive algorithm for Python.
-          In this we have ordered list of 14 numbers, indexed from 0 to 13.
-          We want to find the index value for one of those numbers.
-          theList = [12, 14, 49, 57, 60, 63, 67, 71, 74, 78, 80, 83, 88, 90]

-          Binary search:
-           
-          >>> def BinSearch(SearchItem, OrderedList, lowIndex, highIndex):
-          if lowIndex > highIndex:
-          return -1
-          midPoint = int((lowIndex + highIndex) / 2)
-          foundItem = OrderedList[midPoint]
-          if foundItem == SearchItem:
-          return midPoint
-          elif SearchItem < foundItem:
-          return BinSearch(SearchItem, OrderedList, lowIndex, midPoint - 1)
-          else:
-          return BinSearch(SearchItem, OrderedList, midPoint + 1, highIndex)
-          SyntaxError: expected an indented block
-          BinSearch(SearchItem = 80, OrderedList = theList,
-          lowIndex = 0, highIndex = len(theList))
-          Since the SearchItem = 80, the algorithm will return the index value of 10.
-          
      Python files:
-          Pickle:

-          Easiest way to save and retrieve information in Python is with the pickle utility.
-          Here is a pickle example using simple list.
-          >>> names = ["sam", "fred", "george", "mary", "alice", "harold", "norma"]
-          >>> import pickle
-          >>> pickle.dump( names, open( "nameFile.txt", "wb" ) )
-          >>> inNames = pickle.load( open( "nameFile.txt", "rb" ) )
-          >>> inNames
-          ['sam', 'fred', 'george', 'mary', 'alice', 'harold', 'norma']
-          >>>kit
-          Simple IO example
-          >>> name = ['w \n', 'g \n', 'q \n', 'k \n']
-          >>> theFile = open(file = 'f.txt', mode = 'w')
-          >>> theFile.writelines(name)
-          >>> theFile = open('f.txt', 'r')
-          >>> for line in theFile:
-                          print(line, end='')
-           
-                         
-          w
-          g
-          q
-          k
-          >>> theFile.close()

-          There are three ways to import a module:
-          >>> from math import sin ## import a named function
-          >>> sin (45.0)
-          0.8509035245341184
-          >>> import math ## import module, but with
-          
            >>> math.tan(45) ## dot notation makes it visible
-          1.6197751905438615
-          >>> from math import * ## import module; make all
-          >>> atan(1) * 4 ## functions directly visible;
-          3.141592653589793 ## notice the result!
-          >>> cos(45.0)
-          0.5253219888177297
-          >>> sqrt(67.0) ## no need for dot notation
-          8.18535277187245

-          Sort example:

-          One of the most frequently used algorithm in programming is that of sorting data.
-          There are many different sort algorithms. Here is example of bubblesort.
-          def bubblesort(theList):
-          “”"Sorts list in place and returns it."”” ## a Python docstring
-          for passesLeft in range(len(theList)-1, 0, -1):
-          for index in range(passesLeft):
-          if theList[index] < theList[index + 1]:
-          theList[index],
-          theList[index + 1] = theList[index + 1],
-          theList[index]
-          return theList

-          Stack class example:

-          class Stack(object): ## extend Python object to create class, Stack
-          def __init__(self): ## define constructor method
-          self.stack = [ ] ## implement constructor method
-          self.count = 0 ## initialize the count of the stack
-          def push(self, object): ## define a stack modifier named Push
-          self.count += 1 ## increment the count of the stack
-          self.stack.append(object) ## implement the Push operation
-          def pop(self): ## define a stack modifier named Pop
-          self.count -= 1 ## decrement the count of the stack
-          return self.stack.pop() ## implement the Pop operation
-          def length (self): ## define a stack query given length of stack
-          return (self.count) ## report on the length of the stack
-          >>>the_stack = Stack() ## create an instance of the stack
-          
       Account class example:

-          class Account(object): ## extends Python class, object
-          num_accounts = 0;
-          def __init__(self, name, balance):
-          "Initialize a new account Instance"
-          self.name = name;
-          self.balance = balance;
-          Account.num_accounts += 1;
-          def __del__(self):
-          "Reference counting method"
-          Account.num_accounts -= 1;
-          def sufficient_funds (self, amount):
-          if self.balance > amount:
-          return True
-          else:
-          return False
-          def deposit (self, amount):
-          self.balance = self.balance + amount;
-          def withdraw (self, amount):
-          if sufficient_funds(amount):
-          self.balance = self.balance - amount;
-          else:
-          print "Insufficient Funds for this Transaction";
-          def inquiry(self):
-          return self.balance;
-          “Save this to a file”
-          >>> from Account import *
-          >>>Sam = Account(“Sam”, 0)
-          >>>print Sam.Name
-          Sam
-          >>>print Sam.Balance
-          0
-          >>> 

-          Windows applications:

-          There are several libraries available for doing this kind of GUI programming.
-          One of the simplest is called tkinter.
-          from tkinter import *
-          msg = Message(text="Text Text Text Text Text?")
-          msg.config(bg='pink', font=('times', 16, 'italic'))
-          msg.pack()

-          mainloop()

-          Assertions:
-          Three kinds of assertions:
-          1. Pre-conditions Required before an operation may begin
-          2. Post-conditions Ensures that the algorithm has completed
-          correctly
-          3. Invariants A set of or range of states that constrains types
-          or variables

-          Assertion examples:

-          >>> def DbC1(a): ##  a precondition and invariant on parameter named a
-          assert a > 0 and a < 120, "Parameter out of range"
-          print (a)
-          >>> def DbC1(a):
-          try:
-          assert a > 0 and a < 120, "Parameter out of range"
-          except:
-          print("AssertionError")
-          else:
-          print(a)
-          >>> def BuildIntegerList():
-          theList = []
-          inputValue = 0
-          while inputValue < 999999: ##  arbitrary maximum value for an element
-          try:
-          inputValue = int(input("Enter an Integer; 999999 to Exit "))
-          except:
-          print ("Bad input type")
-          else:
-          if inputValue >= 999999:
-          return theList
-          theList.append(inputValue)
-          >>> def testForInteger(data): ## can be used on a collection of elements or single element
-          anInteger = 0 ## or whatever type you want to test
-          theType = type(anInteger) ## create a class item for the type to be validated
-          try:
-          d = theType(data) ## is the data of the valid type?
-          except:
-          print ("data is not an integer")
-          else:
-          print ("found an integer")
-          >>> testForInteger("45")
-          found an integer

-          Decorators: For python power programming

-          It is difficult concept for newcomers to Python, but it is major step towards generalization of functionality and reuse of source code.
-          In short, a decorator is a function than can modify another function with specialized behavior.
-          For those who know about the “Decorator Patterns” from pattern-based development, we need to
-          clarify that the decorator in Python is not the same thing. Rather, the Python decorator is closer
-          in behavior to, but not identical to, a Delegation pattern. In the Python literature, this is
-          sometimes called a “wrapped function”.
-          A decorator has particular value when creating a set of reusable assertions (pre-, post-, and
-          invariant conditions) to support DbC. Here is a rather elaborate example of a post-condition,
-          using the decorator in Python. We annotate it line-by-line to make it easier to follow. Recall
-          from our discussion of functions, the example where an outer function can call the inner function.
-          The wrapper function, in this example, is invoked by the outer functionnamed
-          ensurePositivePostCondition.
-          We nest another function called “wrapper” inside the client function. The wrapper is designed to
-          take an unspecified number of arguments and an unspecified number of key-word-arguments.
-          This allows it to be reused as a decorator (and as a post-condition function) for a larger number of
-          other targetFunctions.
-          An assert statement looks at the result of computation in the client we have called targetFunction
-          in the formal parameter and ensures (the post-condition) that it is not negative; it is greater than
-          or equal to zero. If the assertion fails, the program simply aborts with a long string of messages.
-          Otherwise, the program will return the intermediate result for the wrapper function.
-          Having taken the result of the targetFunction, the name and the doc parts, the main function,
-          ensurePositivePostCondition(), allows the result of the client function to be returned as a valid
-          value.
-          >>> def ensurePositivePostCondition(targetFunction):
-          def wrapper(*args, **keyWordArgs):
-          result = targetFunction(*args, ## variable positional arguments
-          **keyWordArgs)  ## variable keyword arguments
-          assert result >= 0, targetFunction.__name__ + "() result is not >= 0"
-          return result
-          wrapper.__name__ = targetFunction.__name__ ## assign target name to wrapper
-          wrapper.__doc__ = targetFunction.__doc__ ## assign target docstrings to wrapper
-          return wrapper ## wrapper-modified target
-          >>> @ensurePositivePostCondition ## an assertion decorator
-          def adder(a, b):
-          return a + b
-          >>> adder(12, 34)
-          46
-          >>> adder(-19, 5)
-          Traceback (most recent call last):
-          File "<pyshell#280>", line 1, in <module>
-          adder(-19, 5)
-          File "<pyshell#276>", line 5, in wrapper
-          assert result >= 0, targetFunction.__name__ + "() result is not >= 0"
-          AssertionError: adder() result is not >= 0

No comments:

Post a Comment