Friday, August 16, 2013

Getting Started...........



Writing the first program with python


Assuming you’ve got Python installed, fire up a shell window and type python to start the interpreter. Here’s a simple script. Just type print 'hello world' and hit return. 

now lets go through the code, print  is a built in python function which takes string values as
an input and writes what ever the input parameter in to the standard output which is the monitor.
Any time you want feedback from Python, use the print statement. As with any language, Python has built-in tools for doing common things, like in this case, printing something out.


Built-in Functions

The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order.
abs (x) -- built-in function
Return the absolute value of a number. The argument may be a plain or long integer or a floating point number.
apply (function, args) -- built-in function
The function argument must be a callable object (a user-defined or built-in function or method, or a class object) and the args argument must be a tuple. The function is called with args as argument list; the number of arguments is the the length of the tuple. (This is different from just calling func(args), since in that case there is always exactly one argument.)
chr (i) -- built-in function
Return a string of one character whose ASCII code is the integer i, e.g., chr(97) returns the string 'a'. This is the inverse of ord(). The argument must be in the range [0..255], inclusive.
cmp (x, y) -- built-in function
Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.
coerce (x, y) -- built-in function
Return a tuple consisting of the two numeric arguments converted to a common type, using the same rules as used by arithmetic operations.
compile (string, filename, kind) -- built-in function
Compile the string into a code object. Code objects can be executed by a exec() statement or evaluated by a call to eval(). The filename argument should give the file from which the code was read; pass e.g. '<string>' if it wasn't read from a file. The kind argument specifies what kind of code must be compiled; it can be 'exec' if string consists of a sequence of statements, or 'eval' if it consists of a single expression.
dir () -- built-in function
Without arguments, return the list of names in the current local symbol table. With a module, class or class instance object as argument (or anything else that has a __dict__ attribute), returns the list of names in that object's attribute dictionary. The resulting list is sorted. For example:
    >>> import sys >>> dir()
    ['sys']
    >>> dir(sys)
    ['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']
    >>>
divmod (a, b) -- built-in function
Take two numbers as arguments and return a pair of integers consisting of their integer quotient and remainder. With mixed operand types, the rules for binary arithmetic operators apply. For plain and long integers, the result is the same as (a / b, a % b). For floating point numbers the result is the same as (math.floor(a / b), a % b).
eval (s, globals, locals) -- built-in function
The arguments are a string and two optional dictionaries. The string argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the dictionaries as global and local name space. The string must not contain null bytes or newline characters. The return value is the result of the expression. If the third argument is omitted it defaults to the second. If both dictionaries are omitted, the expression is executed in the environment where eval is called. Syntax errors are reported as exceptions. Example:
    >>> x = 1 >>> print eval('x+1')
    2
    >>>
This function can also be used to execute arbitrary code objects (e.g. created by compile()). In this case pass a code object instead of a string. The code object must have been compiled passing 'eval' to the kind argument. Note: dynamic execution of statements is supported by the exec statement.
filter (function, list) -- built-in function
Construct a list from those elements of list for which function returns true. If list is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, i.e. all elements of list that are false (zero or empty) are removed.
float (x) -- built-in function
Convert a number to floating point. The argument may be a plain or long integer or a floating point number.
getattr (object, name) -- built-in function
The arguments are an object and a string. The string must be the name of one of the object's attributes. The result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar.
hasattr (object, name) -- built-in function
The arguments are an object and a string. The result is 1 if the string is the name of one of the object's attributes, 0 if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception or not.)
hash (object) -- built-in function
Return the hash value of the object (if it has one). Hash values are 32-bit integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, e.g. 1 and 1.0).
hex (x) -- built-in function
Convert a number to a hexadecimal string. The result is a valid Python expression.
id (object) -- built-in function
Return the `identity' of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. (Two objects whose lifetimes are disjunct may have the same id() value.) (Implementation note: this is the address of the object.)
input (prompt) -- built-in function
Almost equivalent to eval(raw_input(prompt)). As for raw_input(), the prompt argument is optional. The difference is that a long input expression may be broken over multiple lines using the backslash convention.
int (x) -- built-in function
Convert a number to a plain integer. The argument may be a plain or long integer or a floating point number.
len (s) -- built-in function
Return the length (the number of items) of an object. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).
long (x) -- built-in function
Convert a number to a long integer. The argument may be a plain or long integer or a floating point number.
map (function, list, ...) -- built-in function
Apply function to every item of list and return a list of the results. If additional list arguments are passed, function must take that many arguments and is applied to the items of all lists in parallel; if a list is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple list arguments, map returns a list consisting of tuples containing the corresponding items from all lists (i.e. a kind of transpose operation). The list arguments may be any kind of sequence; the result is always a list.
max (s) -- built-in function
Return the largest item of a non-empty sequence (string, tuple or list).
min (s) -- built-in function
Return the smallest item of a non-empty sequence (string, tuple or list).
oct (x) -- built-in function
Convert a number to an octal string. The result is a valid Python expression.
open (filename, mode, bufsize) -- built-in function
Return a new file object (described earlier under Built-in Types). The first two arguments are the same as for stdio's fopen(): filename is the file name to be opened, mode indicates how the file is to be opened: 'r' for reading, 'w' for writing (truncating an existing file), and 'a' opens it for appending. Modes 'r+', 'w+' and 'a+' open the file for updating, provided the underlying stdio library understands this. On systems that differentiate between binary and text files, 'b' appended to the mode opens the file in binary mode. If the file cannot be opened, IOError is raised. If mode is omitted, it defaults to 'r'. The optional bufsize argument specifies the file's desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which is usually line buffered for for tty devices and fully buffered for other files.(1)
ord (c) -- built-in function
Return the ASCII value of a string of one character. E.g., ord('a') returns the integer 97. This is the inverse of chr().
pow (x, y) -- built-in function
Return x to the power y. The arguments must have numeric types. With mixed operand types, the rules for binary arithmetic operators apply. The effective operand type is also the type of the result; if the result is not expressible in this type, the function raises an exception; e.g., pow(2, -1) is not allowed.
range (start, end, step) -- built-in function
This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than end; if step is negative, the last element is the largest start + i * step greater than end. step must not be zero. Example:
    >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> range(1, 11)
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> range(0, 30, 5)
    [0, 5, 10, 15, 20, 25]
    >>> range(0, 10, 3)
    [0, 3, 6, 9]
    >>> range(0, -10, -1)
    [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
    >>> range(0)
    []
    >>> range(1, 0)
    []
    >>>
raw_input (prompt) -- built-in function
The string argument is optional; if present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:
    >>> s = raw_input('--> ') --> Monty Python's Flying Circus
    >>> s
    'Monty Python\'s Flying Circus'
    >>>
reduce (function, list, initializer) -- built-in function
Apply the binary function to the items of list so as to reduce the list to a single value. E.g., reduce(lambda x, y: x*y, list, 1) returns the product of the elements of list. The optional initializer can be thought of as being prepended to list so as to allow reduction of an empty list. The list arguments may be any kind of sequence.
reload (module) -- built-in function
Re-parse and re-initialize an already imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. Note that if a module is syntactically correct but its initialization fails, the first import statement for it does not import the name, but does create a (partially initialized) module object; to reload the module you must first import it again (this will just make the partially initialized module object available) before you can reload() it.
repr (object) -- built-in function
Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval().
round (x, n) -- built-in function
Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so e.g. round(0.5) is 1.0 and round(-0.5) is -1.0).
setattr (object, name, value) -- built-in function
This is the counterpart of getattr. The arguments are an object, a string and an arbitrary value. The string must be the name of one of the object's attributes. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.
str (object) -- built-in function
Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object is that str(object does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string.
type (object) -- built-in function
Return the type of an object. The return value is a type object. There is not much you can do with type objects except compare them to other type objects; e.g., the following checks if a variable is a string:
    >>> if type(x) == type(''): print 'It is a string'
vars () -- built-in function
Without arguments, return a dictionary corresponding to the current local symbol table. With a module, class or class instance object as argument (or anything else that has a __dict__ attribute), returns a dictionary corresponding to the object's symbol table. The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.(2)
xrange (start, end, step) -- built-in function
This function is very similar to range(), but returns an ``xrange object'' instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them) except when a very large range is used on a memory-starved machine (e.g. DOS) or when all of the range's elements are never used (e.g. when the loop is usually terminated with break).

 

 

Syntax wise comparison between python and other languages


Python Differences (comparison based on the syntax)


Python Differences For the most part, Python behaves much like PHP, Perl, Ruby and other languages you may be familiar with. However, there are some important and noteworthy differences. Perhaps the most obvious (and Python aficionados would argue, important) is that line breaks and indentions in your code have meaning in Python.
Whereas PHP and others use a semicolon or other mark to designate the end of a line, Python sees all new lines as, well, new lines. Also where PHP and others use curly brackets to enclose code blocks, Python merely wants the code indented.

 Python forces you to properly indent code blocks and eschews end-of-line punctuation like PHP’s semicolons in favor of simple line breaks. This has some import consequences. First and foremost, it makes Python code much easier to read. The structure of a Python script is a snap to figure out at first glance.

Even if you have no idea what the code is doing, you can tell how it does it just by glancing at it. Python forces neat, well structured code, but it also forces you pay more attention to how you write your code. Consider the following two code snippets, which do very different things:

In the first code block our return statement is indented, and therefore within the if statement. In the second code block we didn’t indent the return statement so that function always returns true, regardless of our if test. Technically, that second function would generate an error because Python expects an indented block after the colon.


You'll find that if you're writing code in any language other than Lisp or some other non-intuitive language (not claiming that C is, but in comparison, certainly) language, the syntax isn't too much of a variable. There are some differences, but nothing that should be considered too abstract, in my opinion. In C, you have to worry about things like pointers and whatnot which is a pain, but I think that more-so straddles the line of memory management than syntax if anything. You mostly have to worry about the differences in usages of semicolons and whatnot.

You'll find that Python is like writing English sentences, or at least writing pseudocode with constraints, which makes it significantly easier than C. Additionally, I wouldn't consider jQuery a language on its own. It's an extension of a language though, just as STL might be considered a particular type of extension to C++, I guess.


Spaces versus Tabs

As the joke goes, the most popular way to write Python code is to indent with spaces. The second most popular way to write Python is with tabs. Most good text editors have an “entab/detab” function which can convert tabs to spaces and vice versa.

The important thing is to be consistent. Don’t mix tab and space indenting in the same script! Doing so will cause Python to throw an error and your code won’t execute.



Thursday, August 15, 2013

Getting started with python

Installing Python on Windows

First, download the latest version of Python 2.7 from the official Website. If you want to be sure you are installing a fully up-to-date version then use the “Windows Installer” link from the home page of the Python.org web site .
The Windows version is provided as an MSI package. To install it manually, just double-click the file. The MSI package format allows Windows administrators to automate installation with their standard tools.
By design, Python installs to a directory with the version number embedded, e.g. Python version 2.7 will install at C:\Python27\, so that you can have multiple versions of Python on the same system without conflicts.

Of course, only one interpreter can be the default application for Python file types. It also does not automatically modify the PATH environment variable, so that you always have control over which copy of Python is run.

Typing the full path name for a Python interpreter each time quickly gets tedious, so add the directories for your default Python version to the PATH. Assuming that your Python installation is in C:\Python27\, add this to your PATH:


 Distribute + Pip

The most crucial third-party Python software of all is Distribute, which extends the packaging and installation facilities provided by the distutils in the standard library. Once you add Distribute to your Python system you can download and install any compliant Python software product with a single command. It also enables you to add this network installation capability to your own Python software with very little work.
To obtain the latest version of Distribute for Windows, run the python script available here: python-distribute
You’ll now have a new command available to you: easy_install. It is considered by many to be deprecated, so we will install its replacement: pip. Pip allows for uninstallation of packages, and is actively maintained, unlike easy_install.
To install pip, simply open a command prompt and run

Virtualenv

After Distribute & Pip, the next development tool that you should install is virtualenv. Use pip

The virtualenv kit provides the ability to create virtual Python environments that do not interfere with either each other, or the main Python installation. If you install virtualenv before you begin coding then you can get into the habit of using it to create completely clean Python environments for each project. This is particularly important for Web development, where each framework and application will have many dependencies.
To set up a new Python environment, change the working directory to where ever you want to store the environment, and run the virtualenv utility in your project’s directory


To use an environment, run the activate.bat batch file in the Scripts subdirectory of that environment. Your command prompt will change to show the active environment. Once you have finished working in the current virtual environment, run the deactivate.bat batch file to restore your settings to normal.

 

 python with other operation systems 

 

if you are having linux operation system  like ubuntu ,debeian, python code can be written as scripts and saved in text files with the .py extension. There’s also a shell interpreter that makes it very easy to get started just by typing python into your shell prompt. For now, that’s what we’ll be using to show some of the basic language principles.
Go ahead and fire up a terminal window and type python. If you have Python installed, you’ll get a message like this:


Tip: The three angle brackets are the standard Python command prompt which lets you know you’re now using the Python interpreter. Any time you see code snippets written with the >>> you know the author is referring to the Python shell.

What is Python ???

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C. The language provides constructs intended to enable clear programs on both a small and large scale. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library. Like other dynamic languages, Python is often used as a scripting language, but is also used in a wide range of non-scripting contexts. Using third-party tools, Python code can be packaged into standalone executable programs (such as Py2exe, or Pyinstaller). Python interpreters are available for many operating systems.

Features

Python is a multi-paradigm programming language: object-oriented programming and structured programming are fully supported, and there are a number of language features which support functional programming and aspect-oriented programming (including by metaprogramming and by magic methods). Many other paradigms are supported using extensions, including design by contract and logic programming.
Python uses dynamic typing and a combination of reference counting and a cycle-detecting garbage collector for memory management. An important feature of Python is dynamic name resolution (late binding), which binds method and variable names during program execution.
The design of Python offers only limited support for functional programming in the Lisp tradition. The language has map(), reduce() and filter() functions, comprehensions for lists, dictionaries, and sets, as well as generator expressions. The standard library has two modules (itertools and functools) that implement functional tools borrowed from Haskell and Standard ML
The core philosophy of the language is summarized by the document "PEP 20 (The Zen of Python)", which includes aphorisms such as:
  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Readability counts.
Rather than requiring all desired functionality to be built into the language's core, Python was designed to be highly extensible. Python can also be embedded in existing applications that need a programmable interface. This design of a small core language with a large standard library and an easily extensible interpreter was intended by Van Rossum from the very start because of his frustrations with ABC (which espoused the opposite mindset).