Python Programming - 1


Introduction
  • Python was designed to be easy to understand and fun to use
  • Name came from Monty Python to indicate fun to use
  • You can build prototypes and tools quickly with Python
  • Python is Interpreted



Environment Setup
  • Download reference https://python.org/download
  • Select a version such as 2.7
  • Install and set up PATH environment variable with “installed directory path>” (c:/python27)
  • Use Python GUI – IDLE as editor


Basic Syntax 
  • no types for variables
  • pthon indentation
          if True:
            print "True"
         else:
           print "False"
    
  • Comments
           Use # to comment
  • Coding in .py file
           python test.py
  • Passing argurmts
            $ python test.py arg1 arg2 arg3
            ——————–
            import sys
            print 'Number of arguments:', len(sys.argv), 'arguments.'
            print 'Argument List:', str(sys.argv)
            ————————



Variable and Data Types 
  • Numbers
        int, long, float
    
  • Strings
          Built-in string class named "str" with many handy features
          ------------------------------    
          str = 'Hello World!'
          print str # Prints complete string
          print str[0] # Prints first character of the string
          print str[2:5] # Prints characters starting from 3rd to 5th
          print str[2:] # Prints string starting from 3rd character
          print str * 2 # Prints string two times
          print str + "TEST" # Prints concatenated string
          print str[-1] # Prints !
          print str[:-3]
          -----------------------------------



  • Lists
           list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
           tinylist = [123, 'john']
           print list # Prints complete list
           print list[0] # Prints first element of the list
           print list[1:3] # Prints elements starting from 2nd till 3rd
           print list[2:] # Prints elements starting from 3rd element
           print tinylist * 2 # Prints list two times
           print list + tinylist # Prints concatenated lists
    



 
  • Python Tuples
           Tuples can be thought of as readonly lists
    
            tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
            tinytuple = (123, 'john')
            print tuple # Prints complete list
            print tuple[0] # Prints first element of the list
            print tuple[1:3] # Prints elements starting from 2nd till 3rd
            print tuple[2:] # Prints elements starting from 3rd element
            print tinytuple * 2 # Prints list two times
            print tuple + tinytuple # Prints concatenated lists
    
           tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
           tuple[2] = 1000 # Invalid syntax with tuple
           list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
           list[2] = 1000 # Valid syntax with list
  • Python dictionary    
           Python's dictionaries are kind of hash table type


 
  • Operator
 
  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators
  • Arithmetic Operators     
        ----------------------------------
        a = 21
        b = 10
        c = 0
        c = a + b
        print "Line 1 - Value of c is ", c
        c = a - b
        print "Line 2 - Value of c is ", c
        c = a * b
        print "Line 3 - Value of c is ", c
        c = a / b
        print "Line 4 - Value of c is ", c
        c = a % b
        print "Line 5 - Value of c is ", c
        a = 2
        b = 3
        c = a**b
        print "Line 6 - Value of c is ", c
        a = 9.0
        b = 2.0
        c = a/b
        print "Line 7 - Value of c is ", c
        ----------------------------------------------


  • Comparison Operator

        ———————————————–

        a = 21
        b = 10
        c = 0
        if ( a == b ):
         print "Line 1 - a is equal to b"
        else:
         print "Line 1 - a is not equal to b"
        if ( a != b ):
         print "Line 2 - a is not equal to b"
        else:
         print "Line 2 - a is equal to b"
        if ( a <> b ):
         print "Line 3 - a is not equal to b"
        else:
         print "Line 3 - a is equal to b"
        if ( a < b ):
          print "Line 4 - a is less than b"
        else:
          print "Line 4 - a is not less than b"
        if ( a > b ):
         print "Line 5 - a is greater than b"
        else:
         print "Line 5 - a is not greater than b"
         a = 5;
         b = 20;
        if ( a <= b ):
         print "Line 6 - a is either less than or equal to b"
        else:
         print "Line 6 - a is neither less than nor equal to b"
        if ( b >= a ):
         print "Line 7 - b is either greater than or equal to b"
        else:
         print "Line 7 - b is neither greater than nor equal to b"
 
         ————————————————-

 
  • Assignment Operator
         ---------------------------------------------------
          a = 21
          b = 10
          c = 0
          c = a + b
          print "Line 1 - Value of c is ", c
          c += a
          print "Line 2 - Value of c is ", c
          c *= a
          print "Line 3 - Value of c is ", c
          c /= a
          print "Line 4 - Value of c is ", c
          c = 2
          c %= a
          print "Line 5 - Value of c is ", c
          c **= a
          print "Line 6 - Value of c is ", c
          c //= a
          print "Line 7 - Value of c is ", c
          ------------------------------------------------------

  • Bitwise Operator
         —————–
         a = 0011 1100
         b = 0000 1101
         a&b = 0000 1100
         a|b = 0011 1101
         a^b = 0011 0001
         ~a = 1100 0011
         << Binary Left Shift
         >> Binary Right Shift
         ——————————-

 
  • Logical Operators
         --------------------------------
          and
          or
          not
         -------------------------------

        Membership Operators
        --------------------------------
        a = 10
        b = 20
        list = [1, 2, 3, 4, 5 ];
        if ( a in list ):
         print "Line 1 - a is available in the given list"
        else:
         print "Line 1 - a is not available in the given list"
        if ( b not in list ):
         print "Line 2 - b is not available in the given list"
        else:
         print "Line 2 - b is available in the given list"
         a = 2
        if ( a in list ):
         print "Line 3 - a is available in the given list"
        else:
         print "Line 3 - a is not available in the given list"
        ------------------------------------
ez

  • Identity Operators
        —————————————
 
        a = 20
        b = 20
        if ( a is b ):
         print "Line 1 - a and b have same identity"
        else:
         print "Line 1 - a and b do not have same identity"
        if ( id(a) == id(b) ):
         print "Line 2 - a and b have same identity"
        else:
         print "Line 2 - a and b do not have same identity"
         b = 30
        if ( a is b ):
         print "Line 3 - a and b have same identity"
        else:
         print "Line 3 - a and b do not have same identity"
        if ( a is not b ):
         print "Line 4 - a and b do not have same identity"
        else:
         print "Line 4 - a and b have same identity"

         —————————————————-


 
  • Conditional Statements
           if statements
           if else
           nested if

           var = 100
           if var == 200:
            print "1 - Got a true expression value"
            print var
           elif var == 150:
            print "2 - Got a true expression value"
            print var
           elif var == 100:
            print "3 - Got a true expression value"
            print var
           else:
            print "4 - Got a false expression value"
            print var
            print "Good bye!"



  • Loops
            while
            while .. else


           count = 0
           while count < 5:
            print count, " is less than 5"
            count = count + 1
          else:
           print count, " is not less than 5"
 
         
           For

           for letter in 'Python': # First Example
            print 'Current Letter :', letter
            fruits = ['banana', 'apple', 'mango']
           for fruit in fruits: # Second Example
            print 'Current fruit :', fruit
            print "Good bye!"
            fruits = ['banana', 'apple', 'mango']
           for index in range(len(fruits)):
            print 'Current fruit :', fruits[index]
            print "Good bye!"




           Nesting of loops
           
            i = 2
            while(i < 100):
            j = 2
            while(j <= (i/j)):
            if not(i%j): break
            j = j + 1
            if (j > i/j) : print i, " is prime"
            i = i + 1
            print "Good bye!"


           Loop Control Statements
           break
           continue
           pass



  • Functions
         ———————————————-
           # Function definition is here
           def printme( str ):
           "This prints a passed string into this function"
            print str;
            return;
            # Now you can call printme function
            printme("I'm first call to user defined function!");
            printme("Again second call to the same function");
            ————————————————–
     
             Pass by reference
            ———————————–
            # Function definition is here
            def changeme( mylist ):
            "This changes a passed list into this function"
             mylist.append([1,2,3,4]);
             print "Values inside the function: ", mylist
             return
             # Now you can call changeme function
              mylist = [10,20,30];
              changeme( mylist );          
              print "Values outside the function: ", mylist
              —————————————–

              Function Arguments
              You can call a function by using the following types of formal arguments:
  •     Required arguments
  •     Keyword arguments
  •     Default arguments
  •     Variable-length arguments

             ————————————
             # Function definition is here
             def printinfo( name, age = 35 ):
             "This prints a passed info into this function"
             print "Name: ", name;
             print "Age ", age;
             return;
             # Now you can call printinfo function
             printinfo( age=50, name="miki" );
             printinfo( name="miki" );
             ——————————————————

             Variable-length arguments

             ——————————————————

             # Function definition is here
             def printinfo( arg1, *vartuple ):
             "This prints a variable passed arguments"
              print "Output is: "
              print arg1
              for var in vartuple:
              print var
              return;
              # Now you can call printinfo function
              printinfo( 10 );
              printinfo( 70, 60, 50 );

              ————————————————


ittc
  • Scope of Variables
             -------------------------------------------------
            total = 0; # This is global variable.
            # Function definition is here
            def sum( arg1, arg2 ):
            # Add both the parameters and return them."
            total = arg1 + arg2; # Here total is local variable.
            print "Inside the function local total : ", total
            return total;
            # Now you can call sum function
            sum( 10, 20 );
            print "Outside the function global total : ", total 
            -----------------------------------------------------------
  • Modules
            import mod1 => importing mod1.py (Refer pdf)
  • INPUT/OUTPUT

           s = raw_input("enter something")
           print "you entered:", s

           s = input("enter something")
           print "you entered:", s
  • Opening and Closing Files
           fo = open("c:/testing.txt", "r")
           str = "qqqq"
           while(str):
           str = fo.next()
           print str
           fo.close()
  • Exceptions
            try:
            fh = open("testfile", "w")
            fh.write("This is my test file for exception handling!!")
            except:
            # except IOError:
            print "Error: can\'t find file or read data"
            else:
            print "Written content in the file successfully"
            fh.close()
 
           ------------------------------------------------------------------------------------
 
Edited

Rating

Unrated
Rating:

Critical error – bailing out

This is an error that has been elevated to critical error status because it occurred during the primary error mechanism reporting system itself (possibly due to it occuring within the standard output framework). It may be masking a secondary error that occurred before this, but was never output - if so, it is likely strongly related to this one, thus fixing this will fix the other.
Unfortunately a query has failed [DELETE FROM ocp_stats WHERE date_and_time<1702915629] [Table 'ocpo1.ocp_stats' doesn't exist] (version: 9.0.20, PHP version: 5.6.40, URL: /site/index.php?page=news&type=view&id=csc-presentation%2Fpython-programming-1&filter=31)

Details here are intended only for the website/system-administrator, not for regular website users.
» If you are a regular website user, please let the website staff deal with this problem.

Depending on the error, and only if the website installation finished, you may need to edit the installation options (the info.php file).

ocProducts maintains full documentation for all procedures and tools. These may be found on the ocPortal website. If you are unable to easily solve this problem, we may be contacted from our website and can help resolve it for you.


ocPortal is a CMS for building websites, developed by ocProducts.