How I may help
LinkedIn Profile Email me!

Reload this page Python Programming

Here are concise notes on the Python script programming language, combining the knowledge and wisdom from various news groups, books, help files, training documents, etc. — arranged in my own way, but with all text in this one large file for quick search through all topics.

webpage article Google Computers > Programming > Languages > Python

Why Python?

There are a lot of technical merits. But the largest is that it's the language for Google has chosen to build Google Apps running within the Google cloud.

 

Topics this page:

  • Language History
  • Starting the Env.
  • Development Workflow
  • Source Syntax Basics
  • Source Files
  • Built-in functions
  • Import Module
  • Documentation
  • Folders, Files
  • IDEs, Debugging
  • Programming Utilities
  • Instances, Libraries
  • Algorithms
  • Interfaces, Coding, Identifiers, Data Structures
  • Collections
  • Resources
  • Your comments???

  •  

    Site Map List all pages on this site 
    About this site About this site 
    Go to first topic Go to Bottom of this page


    Set screen Language History

      The Python language is not named after a reptile, but the British TV series "Monty Python's Flying Circus", which ran from 5 Oct 1969 to 1973 on BBC-1 and on BBC-2 (without Cleese) until 5 Dec 1974. The show featured surreal sketch comedy by many of Britain's most well-known commedians who went on to create "Monty Python and the Holy Grail" and other silly movies. They are: Graham Chapman, John Cleese, Terry Gilliam, Terry Jones, Michael Palin, and Eric Idle,

        The name of the Python GUI IDE (that comes with Linux) is the acronymn IDLE.

      Versions to 1.2 were created during 1991-1995 principally by Guido van Rossum at the Stichting Mathematisch Centrum (CWI) in the Netherlands. This is noted in the first prompt when Python starts. — Guido van Rossum and Jelke de Boer, "Interactively Testing Remote Servers Using the Python Programming Language", CWI Quarterly, Volume 4, Issue 4 (December 1991), Amsterdam, pp 283-303.

      Versions to 1.6 during 1995-2001 were created by Guido at CNRI (Corporation for National Research Initiatives) in Reston, Virginia.

      Version 2.0 in 2000 was released for the first time via SourceForge by Guido's PythonLabs team at BeOpen.com.

      Version 2.1 and beyond (2001 on) become owned by the non-profit Python Software Foundation (PSF) modeled after the Apache Software Foundation. This happened after Guido's team moved to Digital Creations, which became Zope (which offers CMS and Intranets).

      The Server Side on Python

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Python Run Environments

      There are two ways to run Python.

      Python is an "interpretive" language like Unix shell scripts and Windows command files, which executes immediatelyon this page one line at a time.

      In contrast, Java is a "compiled' language.

      Jpython provisions Java programs to run Python programming code.

      But be aware of differences among implementations, which do not fullly implement all the standard python libraries.

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Installers

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Starting the Python Environment

      Python was designed to be interpreted and immediately executed (without a compile step like C and Java).

      The ActiveState version 2.4 installer creates folder C:\Python24\

      Since the installer puts that folder in the PATH environment variable, you can start it from any folder.

        python -h

      Start Flags

      Here is the listing when Python is started with the -h (help) flag:

      usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
      Options and arguments (and corresponding environment variables):
      -c cmd : program passed in as string (terminates option list)
      -d     : debug output from parser (also PYTHONDEBUG=x)
      -E     : ignore environment variables (such as PYTHONPATH)
      -h     : print this help message and exit
      -i     : inspect interactively after running script, (also PYTHONINSPECT=x)
               and force prompts, even if stdin does not appear to be a terminal
      -m mod : run library module as a script (terminates option list)
      -O     : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)
      -OO    : remove doc-strings in addition to the -O optimizations
      -Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew
      -S     : don't imply 'import site' on initialization
      -t     : issue warnings about inconsistent tab usage (-tt: issue errors)
      -u     : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x)
               see man page for details on internal buffering relating to '-u'
      -v     : verbose (trace import statements) (also PYTHONVERBOSE=x)
      -V     : print the Python version number and exit
      -W arg : warning control (arg is action:message:category:module:lineno)
      -x     : skip first line of source, allowing use of non-Unix forms of #!cmd
      file   : program read from script file
      -      : program read from stdin (default; interactive mode if a tty)
      arg ...: arguments passed to program in sys.argv[1:]
      Other environment variables:
      PYTHONSTARTUP: file executed on interactive startup (no default)
      PYTHONPATH   : ';'-separated list of directories prefixed to the
                     default module search path.  The result is sys.path.
      PYTHONHOME   : alternate  directory (or ;).
                     The default module search path uses \lib.
      PYTHONCASEOK : ignore case in 'import' statements (Windows).
      

      Start Options

      Python starts by executing the contents of a file identified by the PYTHONSTARTUP environment variable.

      So Python can be started by:

        python

      Pressing Ctrl+Z and Enter/Return exits from Python.

      Python can be invoked with commands followed by "-c", or modules followed by "-m".

      Just for Windows

      Idea I don't use PYTHONCASEOK (provided for looser case sensitivity on Windows platforms) because this leads to "sloppy" coding which reduces the portability of code among operating systems.

      The >>> Interactive Prompt

      Python's interactive Mode prompt >>> can be used like a calculator.

      So you can test language features while you're programming.

      Python does not require variable or argument declarations. Unlike languages such as C and Java, you don't need to declare variables with their datatypes before using them. This is because Python (and VBScript) are called "dynamically typed" languages since Python figures out at time of execution what datatype a variable is when it is first assigned, rather than at time of compilation (such as "statically typed" languages like C and Java).

      within Python (and Java), you cannot (without any explicit conversion) concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123. Unlike the "weakly typed" VBScript language, Python is called a "strongly typed" languages becuase it always enforces types. If you have an integer, you can't treat it like a string without explicitly converting it.

      To list what functions have been defined ...

      The Main Module

      Python begins by executing code such as this usually at the bottom of the main module:

          if __name__=="__main__":
              main_logic()
      

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Python Source Code Basics

      Like the show, which "offered savage broadsides against the pomposity and repression of the British establishment." the Python language aims to offer an improvement to C and Java.


      # hello.py - Wilson Mar - 24oct2005
      # Some simple program
      
      def func1():
      	pass
      def func2():
      	pass
      dispatch = {'go': func1, 'stop': func2}  
          # Note lack of parens for funcs
      
      dispatch[get_input()]()  
          # Note trailing parens to call function
      
      def func2(a, b):
          a = 'new-value'
          b = 0xa5 + 1  # Hex decimal 165+1
          c = 010 # Octal 10 = decimal 8
          d = x010 # Octal 10 = decimal 8
          return a, b
      
      while True:
          line = f.readline()
          if not line:
              break
          #...do something with line...
      
      for line in f:
          # do something else
      
      
      After The colon is the doc string, treated the __doc__ attribute of the function.

      Python coders can avoid continuation and escape characters because, with Python, multi-line string blocks are within as set of triple double-quotes.

      # begins comments (as with C). It can't follow a continuation character on the same line.

      Instead of semicolons at the end of each expression (as with C or Java), like VBScript
      Python uses a carriage return to separate statements.

      Python uses {} curly braces to define dictionaries.
      To separate code blocks Python uses indentation (4 spaces) to delimit statement groups. Sequential lines indented at the same level are treated as the same block.

      To continue a line, add a \ back slash and indent the following line.

      "..." elipses (3 periods) precedes each multi-line construct.

      Python's high-level data types allow complex operations to be expressed in a single statement.

      The Python community has a saying: “Python comes with batteries included.” Python is extensible: functions can be added by adding modules.

      The pass statement does nothing.

      A leading '0' (zero) indicates octal, '0x' indicates a hex number, '\u' goes in front of hex Unicode code point.

      "_" (the underline character) stands in for the last variable used (read-only).

      "\" backslash character at the end of a line is used to specify continuation to the next line.

      "\n" is an escape character for "next line" (not necessary between triple quotes).

      "\\" is thus necessary to specify back-slash separators between folders in a directory path.

      "+" is used to concantenate strings (rather than the amersand & in C).

      Strings can be encased between either double or single quotes.

      Unlike C, assignments are not allowed within expressions.

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Python Source Files

      >>> import tck.hello.py
      Traceback (most recent call l
        File "", line 1, in
      ImportError: No module named
      

      >>> import tck-hello.py File "", line 1 import tck-hello ^ SyntaxError: invalid syntax

      Python source modules are saved by editors and IDEs as files suffixed with .py. But this does not need to be specified when importing a module.

      Reminder When naming modules, do not use special characters such as a period or a dash, which have special meaning to python.

      When a module is imported for the first time (or when the source is more recent than the current compiled file) Python parses and translates it into a bytecode files suffixed with .pyc in the same folder as the source file.

      Reminder You will not see the >>> prompt while a called module is running. On Windows, press Alt+Tab to switch to the app's window.

      Python scripts are made into an executable Windows script when its named with a .cmd suffix and contains this first line:

        @setlocal enableextensions & python -x %~f0 %* & goto :EOF

      Python scripts are made into a UNIX script by putting in the first line a directive containing the path where the Python interpreter is located. This example uses an absolute path:

        #!/usr/local/bin/python

      Source Structure

      Jim Roskind suggests ordering various types of code in this order within modules:

      • exports (globals, functions, and classes that don't need imported base classes)
      • import statements
      • active code (including globals that are initialized from imported values).

      Intermingling Source

      To intermingle Python and C code to increase performance:

      • Pyrex compiles a slightly modified version of Python code into a C extension, for use on many different platforms.
      • Psyco is a just-in-time compiler that translates Python code into x86 assembly language. If you can use it, Psyco can provide dramatic speedups for critical functions.
      • PyInline
      • Py2Cmod
      • Weave

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Built-in Names (Modules, Functions, Variables)

      dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.

      >>> L = [] # add the name "L" to the local namespace, making it refer to an empty list object.
      >>> dir(L)
      ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

      >>> a={} # empty dictionary.
      >>> dir(a)
      ['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'update', 'values']

      >>> import __builtin__
      >>> dir(__builtin__)
      ['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Imports

      Python scripts import modules only from directories specified in the PYTHONPATH environment variable. On Unix, this is usually .:/usr/local/lib/python. Internally, this is variable sys.path, which can be changed with code such as:

        >>> import sys

        >>> sys
        <module 'sys' (built-in)<

        >>> sys.path.append('/ufs/guido/lib/python')
        >>> sys.path
        ['', '/usr/local/lib/python2.2',
        '/usr/local/lib/python2.2/plat-linux2',
        '/usr/local/lib/python2.2/lib-dynload',
        '/usr/local/lib/python2.2/site-packages',
        '/usr/local/lib/python2.2/site-packages/PIL',
        '/usr/local/lib/python2.2/site-packages/piddle']

      On a Windows machine:

        >>> sys.path
        ['',
        'C:\\WINDOWS\\system32\\python24.zip',
        'C:\\Documents and Settings\\W',
        'C:\\Python24\\DLLs',
        'C:\\Python24\\lib',
        'C:\\Python24\\lib\\plat-win',
        'C:\\Python24\\lib\\lib-tk',
        'C:\\Python24',
        'C:\\Python24\\lib\\site-packages',
        'C:\\Python24\\lib\\site-packages\\win32',
        'C:\\Python24\\lib\\site-packages\\win32\\lib',
        'C:\\Python24\\lib\\site-packages\\Pythonwin']

      Idea It is good practice to import modules in this order:

      1. standard libary modules: sys, os, getopt, re.
      2. third-party library modules (anything installed in Python's site-packages directory): mx.DateTime, ZODB, PIL.Image, etc.
      3. locally-developed modules

      After you change a module, force rereading:

        import modname
        reload(modname)

        Reminder This does not affect modules which use:

        from modname import *

        So avoid using the above. They also clutter the namespace.

      Also avoid circular imports ...

      Arguments are passed by assignment in Python.

      To issue a prompt and accept an input from the user:

        >>> x = int(raw_input("Please enter an integer: "))

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

      Set screen Standard Library Modules

      Module Purpose
      getopt >>> dir(getopt)
      re >>> dir(re)
      os >>> dir(os)
      sys >>> dir(sys)
      ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions']

    Go to Top of this page.
    Previous topic this page
    Next topic this page

      Set screen GUI Libraries

      Python's de-facto standard the most commonly used GUI toolkit is iTkinter (short for "Tk interface"). It is a thin object-oriented layer on top of Tcl/Tk from Scriptics.

      Tk originated from Sun Labs. Today it's available on most Unix and Macintosh platforms. Since release 8.0. a dll provides Windows native look and feel, which looks fine.

      Tkinter consists of, among many modules, Tkconstants and the Tk low-level interface binary module _tkinter (which should never be used directly by application programmers).

      Tk is event driven



    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Documentation

      Follow PEP 257 conventions and styles.

      The first line should always be a short, concise summary of the object's purpose. For brevity, it should not explicitly state the object's name or type, since these are available by other means (except if the name happens to be a verb describing a function's operation). This line should begin with a capital letter and end with a period.

      If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description. The following lines should be one or more paragraphs describing the object's calling conventions, its side effects, etc.

      If markup your source in structured-text docstrings format, you can use

      webpage article Python.org Main doc page

     

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Compiling

      Modules compiled with the -O Optimization flag (which causes asserts and __doc__ strings to be removed) are suffixed with .pyo.

      __main__ modules don't become .pyc modules. But you can force compile with:

        >>> import py_compile
        >>> py_compile.compile('xxx.py')

      .pyc files are written to the same location as .py file unless override with the optional parameter cfile.

      To compile all files in a directory or directories:

        python compileall.py

        You will be prompted for the directory path.

     

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Unit Testing and Debugging Python Programs

      First, use a static analysis tool to find syntactic bugs in Python source code. These tools also warns about code complexity and style.

      • PyChecker
      • Pylint also ensure satisfaction with coding standard (such as PEP 8, the standard for writing Python library modules). Standards defined in plug-ins include line length, whether variable names are well-formed according to your coding standard, whether declared interfaces are fully implemented, etc.

      "pdb" is the default console debugger.

      The doctest module finds examples in the docstrings for a module and runs them, comparing the output with the expected output given in the docstring.

      The unittest module PyUnit.sourceforge.net testing framework is modelled after Kent Beck's JUnit and smalltalk testing framework.

     

      tool The FXCop for C# programs code analysis tool checks .NET managed code assemblies for conformance to Microsoft .NET Framework Design Guidelines and custom rules created by the provided SDK.

      It uses reflection, MSIL parsing, and callgraph analysis to inspect assemblies for more than 200 defects

      The tool has both GUI and command line versions,

      ErrorBank, the .NET Error Repository crawler browses newsgroups and tries to collect only threads that have a description of an error/exception and solution to the problem discussed by developers.

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen IDEs (Integrated Development Environments)

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Utilities For Python Source Code

    • Decompilers reverse engineering from executables back into (difficult to read) source:
    • C class file obfuscators reduce the size of C class files while it blocks decompilers.
    • Code Formatters:
    • Code Profilers analyze code execution to provide a time-aware view of a program's execution, to easily identify sluggish function bottlenecks.
    • Test Coverage tools reveal which lines of source code were executed during tests.
    • PDF publishing

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Working Folders

      For a list of folders in the current directory:

      	>>> import os # POSIX module
      	>>> os.listdir('.')
      

      To create a new folder (and any intermediate directories which don't exist):

      	>>> os.makedirs( path )
      

      To remove a directory (and any intermediate directories which are empty):

      	>>> os.removedirs( path )
      

      To remove a directory:

      	>>> os.rmdir()
      

      To delete an entire directory tree and its contents:

      	>>> shutil.rmtree()
      

      The shutil module also has copyfile, copytree, rmtree, and other file functions.

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Working Files

      To open a file using a built-in low-level function to get a small integer file handle for read only):

      	>>> f = open( filename, "r+")
      

      To read a file opened by the statement above:

      	>>> os.read()
      

      To open a file using a high-level function to get a small integer file handle for read only):

      	>>> f = os.popen( filename, "r+")
      

      To read n bytes from a pipe p created with os.popen():

      	>>> p.read( n )
      

      To truncate a file from the current offset seek position:

      	>>> f.truncate( offset ); 
      

      To rename a file:

      	>>> os.rename( old_path, new_path)
      

      To delete a single file:

      	>>> os.remove(filename)
      

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Database Access

       >>> import odbchelper
       >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
       >>> print odbchelper.buildConnectionString(params) 
       server=mpilgrim;uid=sa;database=master;pwd=secret
      

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Accessing Console

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Mo' Class Libraries



    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Performance Algorithms

     

    The Deitel Family's books are wordy and expensive ($75), but colorful.

    C#, How to Program

    C# For Experienced Programmers

    JoeGrip says you can learn C# in just 5 hours with their interactive audio courses online.

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Interfaces

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Sub classes

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Object Identifier Naming & Duration

      The identifiers used to name variables and references include attributes name, data type, size, and value.

      Reminder Identifiers must start with a letter, $ or _ (underline), but not a number.
      Reminder Uppercase and lowercase alphabetic characters are differentiated.

      The state of an object is determined by the values stored in its variables.

      An identifier's duration in memory is also called its lifetime.

      • Member Variables of a class are created (instantiated) when an instance is created by invoking a new constructor. It is subject to accessibility rules and the need for a reference to the object.

        Stored in the heap, member variables are accessible as long as the enclosing object exists They are destroyed when the object is destroyed. The space they consumed are then recovered by C's garbage collection mechanisms.

      • Automatic Variables of a method are created on entry to the method (when the method is invoked). They exist only during execution of the method, and therefore is only accessible during the execution of that method. Thus, they are also known as local variables. So, local variables have automatic duration.

        Stored in the stack, they must be explicitly initialized before being used (to avoid a compiler error). They are destroyed on exit from the method.

      The keyword this. is used to reference local variables named the same as variables defined at the class instance level. This is not valid for static methods.

      An identifier's scope defines where the identifier can be referenced within a program.

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Lists

      Python's lists are really variable-length arrays implementated as a contiguous array of references to other objects. A list head structure keeps a pointer to the array and the array's length.

      This gives Python its cool feature: sequences can be indexed with negative numbers.

      0 starts is the first number, as with C and Java.
      -1 is the last index
      -2 is the pentultimate (next to last) index.

      Think of seq[-n] as the same as seq[len(seq)-n].

      S[:-1] is all of the string except for its last character — useful for removing the trailing newline from a string.

      Tuples - Dictionaries - hash

      Tuples are small collections of related data operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers.

      Tuples are immutable: once a tuple has been created, it can't be replaced with a new value. Tuples can be used as keys because only immutable elements can be used as dictionary keys, which are implemented as resizable hash tables. Its members may be of different types.

      Dictionaries work by computing a hash code for each key stored in the dictionary using the hash() built-in function. The hash code varies widely depending on the key; for example, "Python" hashes to -539294296 while "python", a string that differs by a single bit, hashes to 1142331976. The hash code is then used to calculate a location in an internal array where the value will be stored. Assuming that you're storing keys that all have different hash values, this means that dictionaries take constant time -- O(1), in computer science notation -- to retrieve a key. It also means that no sorted order of the keys is maintained, and traversing the array as the .keys() and .items() do will output the dictionary's content in some arbitrary jumbled order.

      In Python, strings are immutable. Once defined, they can't be changed.

      However, individual elements of a list can be redefined:

      >>> s = "Hello, world"
      >>> a = list(s)
      >>> print a
      ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
      >>> a[7:] = list("there!")
      >>> ''.join(a)
      'Hello, there!'
      
      It's faster to use the array module can be used:

      >>> import array
      >>> a = array.array('c', s)
      >>> print a
      array('c', 'Hello, world')
      >>> a[0] = 'y' ; print a
      array('c', 'yello world')
      >>> a.tostring()
      'yello, world'
      

      You can use slice notation to insert a copy of itself at the beginning of list b:

        >>> b[:0] = b

      With slice, starting and ending locations (starting from zero): two indices separated by a colon. Negative numbers count from the right.

      With print, a space is automatically inserted between items. And a newline is inserted before the next prompt if the last line was not completed.

      One neat Python trick is multiplication of strings:

        >>> "Hello" * 3
        HelloHelloHello

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

      Set screen Object modifiers

      A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a datatype. A class can be based on one or more other classes, called its base class(es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined by inheritance.

      In addition to keywords main, void, static defined above:
      Object
      Scope
      Modifier
      keyword
      Purpose

      native

      method bodies are found outside the JVM, usually in a library written in C++ or other low-level language. Native method declarations are ended with a semi-colon and not curly braces having no body, indicating that the implementation is not provided in the class.

      abstract

      classes and methods are not instantiated by the new constructor so that implementation is deferred to a subclass. The compiler requires a class to be abstract if any of its methods is abstract. However, an abstract class can have non abstract methods.

      final

      defined in a superclass (or interface) a constant specified with an initial value that cannot be changed. Final classes can't be sub-classed (extended) and must be overridden by the implementing class. Such static variables are usually in upper case and referenced by the class name as a prefix. A final variable must have an initial value or may be initialized in every constructor.

      transient

      variables are not stored as part of its object's persistent state. Such objects may implement the Serializable or Externalizable interfaces to have their state serialized and written to destinations outside the JVM by passing the object to the writeObject() method of the ObjectOutputStream class.

      volatile

      variables might be modified asynchronously in multiprocessor environments.

      Set screen Inner Classes

      Class ModifierPurpose

      static

      methods and variables are called class methods and variables because they are associated with the class itself rather than an instance of that class. Methods cannot be declared inside a static block. So static members and variables are referenced by class name rather than instance name. Inside a static method there is no this reference to an instance. Static methods can't be overridden. Static methods, variables, and blocks of code are created only once for all instances to share.

      static inner

      have access to the static members of the enclosing class, even to those that are private. They do not have implicit reference to members of the instances of the enclosing class.

      member inner

      (not static) can access all the members of the enclosing class, even if they are protected or private.

      local inner

      specified within a method definition of the enclosing class. It cannot be declared as static, public, protected, or private. It can access local variables that are specified as final.

      Anonymous inner

      are use just once and not again. They do not have a class name / constructors. They can access final local variables

      The synchronized modifier is used to control access to critical code in multi-threaded programs.

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Developer Resources

      Certification

      Tutorials

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Style Guides: "Pythonic" syntax Numbers

      Python has no ternary operator such as with "a?b:c" in C.

      Python has no if-then-else expression since "it can easily lead to less readable code".

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Handing Large Numbers with Epsilon

      Python has a neat feature called an "epsilon":

      str(23) yields 23.
      oct(23) yields '027' (strings with a leading "0" are interpreted as octals).
      hex(23) yields '0x17' (strings with a leading "0X" are intrepreted as hex).

      When comparing two very large or small numbers, a regular == operator would fail because of small differences.

        >>> 0.2
        0.20000000000000001

      So check whether the difference between the two numbers is less than a certain threshold: the epsilon.

      epsilon = 0.0000000000001 # Tiny allowed error
      expected_result = 0.4
      if expected_result-epsilon <= computation() <= expected_result+epsilon:
      

     

      Go to Top of this page.
    Previous topic this page
    Next topic this page

    Portions ©Copyright 1996-2004 Wilson Mar. All rights reserved. | Privacy Policy |


    Related Topics:
    another page on this site Keyboard Shortcuts 
    another page on this site Project Software 
    another page on this site Project Central 

    another page on this site Free Training! 
    another page on this site Tech Support 


    How I may help

    Send a message with your email client program


    Your rating of this page:
    Low High




    Your first name:

    Your family name:

    Your location (city, country):

    Your Email address: 



      Top of Page Go to top of page

    Thank you!