Python (programming language)

Python is a high-level, open-source programming language that can be used for many different tasks in a wide range of application domains. Python was created by Guido van Rossum in the early 1990s and it has since grown to become very popular.

Python supports multiple programming paradigms, including object-oriented, imperative and functional programming styles. It comes with a large and comprehensive standard library, with thousands of third party modules also available.

Python is very portable and has distributions available for Microsoft Windows, Apple Mac OS X, GNU/Linux, BSD and many other platforms. There are currently three major implementations: the standard implementation written in C, Jython written in Java, and IronPython written in C# for the .NET environment.


Programming Paradigms

Python fully supports object-oriented programming. Classes can be defined using the class statement, and methods have an explicit 'self' parameter to access instance data.

While Python is not specifically designed for functional programming, it has been influenced by functional languages, such as Lisp and Haskell. As a result, it has many features suitable for use in a functional style, including the map(), filter() and reduce() built-in functions; list, dictionary and set comprehensions; lambda expressions; and generators. Python 3 has also provided an increasing emphasis on lazy evaluation.


Python uses a style of dynamic typing called duck typing. The language has typed objects but untyped variable names, so a variable can refer to a value of any type. Type constraints are not checked beforehand, but operations on an object may fail if it is not of a suitable type. Python is strongly typed, forbidding operations that are not well-defined (for example, adding a number to a string) rather than silently attempting to make sense of them.

Memory Management

Python uses a combination of reference counting and a cycle-detecting garbage collector for memory management. Reference counting tracks, for each object, a count of the number of references to it held by other objects. If an object's reference count reaches zero, the object has become inaccessible and can be destroyed. One of the problems with reference counting is that when two or more objects refer to each other, they can create a cycle (or endless loop) whereby neither will be collected as their mutual references never let their reference count become zero. Python overcomes this issue by using a cycle detector to search for both direct and indirect circular references.


Python uses whitespace indentation, rather than curly braces or keywords, to delimit blocks. An increase in indentation comes after compound statements such as the if, while and def statements. A decrease in indentation signifies the end of the current block. The Python style guide recommends using four spaces for indentation, although any number of spaces or tabs will work as long as they are used consistently throughout each block. While some consider the significance of whitespace to significantly enhance readability, others have criticised it.

Interactive Mode

Python has two basic modes: normal and interactive. Normally, a complete '.py' file is passed to the interpreter to be run. When no arguments are given, python will enter interactive mode.

Since Python is an interpreted language, the interpreter is able to run each statement individually as it is entered in interactive mode. This allows feedback or output from a statement to be received before the next one is entered. As new lines are fed into the interpreter, they are evaluated in the context of the whole session so far.

A sample interactive session:

>>> 5
>>> print 5*7
>>> "hello" * 4
>>> "hello".__class__
<type 'str'>

Interactive mode can be used to do quick calculations or execute short programs without having to create a file. Typing help() at the prompt will bring up the interactive help utility, which is very useful for learning or just checking the documentation. Information on a specific object or command can be obtained by passing a parameter to the help function, such as help('object').


Rather than requiring all desired functionality to be built into the language's core, Python was designed to be highly extensible. The language makes heavy use of modules, allowing one program to easily import scripts from many other files.

Extension modules provide a way for Python to use modules of code that can be written in a variety of other languages. The documentation provides a tutorial on extending Python with C or C++.

Design Philosophy

Python's design philosophy puts a strong emphasis on minimalism and code readability. It is best expressed in The Zen of Python, which can be viewed in the Python interpreter by importing the module named 'this'.

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let's do more of those!

In the Python community, the term pythonic is often used to describe code that conforms well with these principles.


Since Python is an interpreted language, it will never be able to compete with compiled languages in terms of speed. Consequently, performance is not considered a high priority in Python, with clarity and code readability usually taking precedence.

Fortunately, there are a number of options available for when speed is important. PyPy is an alternative implementation of Python that makes use of a just-in-time compiler for significant performance gains. Time-critical functions are often moved to extension modules that can be written in faster languages such as C. Cython can also be used to translate Python into C extension modules, allowing for optimisations like static type declarations.

Python 3

Python 3, a major, backwards-incompatible release, was released in December 2008 after a long period of testing. The release brought many significant improvements to the language, removing inconsistencies and making it easier for people new to programming.

Some of the noteworthy changes include:

  • The print and exec statements were converted to built-in functions
  • Several built-in functions were updated to use lazy evaluation for greater memory efficiency
  • The division operator was updated to use floating point division, with a new operator being introduced for integer division
  • Unicode received an overhaul
  • Large improvements for many modules in the standard library
  • Some minor changes to the syntax


Python is suited for many different tasks in a variety of areas. Its users range from individuals to large organisations including Google, Yahoo!, CERN and NASA. Python is often used in scientific computing and the information security industry. It is a common scripting language for both the desktop and web applications. There are many web application and network frameworks available that use Python, such as Django and Twisted. It is also embedded in a number of applications, like Blender, for use as a scripting language.


Hello World

Python's simplicity and lack of required boilerplate code makes it a common choice for new programmers. The simplicity of the language is evident in its version of the "Hello world" program:

print 'Hello, world!'

Note: Python 2 is used for all examples. In Python 3, print is a function, so parentheses would be required around the string.

Simple Program

A simple program that demostrates exception handling, input and list comprehensions:

    num = int(raw_input('Enter a number: '))
    squares = [n ** 2 for n in range(1, num + 1)]
    total = sum(squares)
    print total
except ValueError:
    print 'That is not a number.'


A brief example of object-oriented programming in Python:

class BankAccount(object):
    def __init__(self, initial_balance=0):
        self.balance = initial_balance
    def deposit(self, amount):
        self.balance += amount
    def withdraw(self, amount):
        self.balance -= amount
    def overdrawn(self):
        return self.balance < 0
my_account = BankAccount(15)
print my_account.balance


Using recursion to calculate the factorial of a number:

def factorial(n):
    if n < 2:
        return 1
        return n * factorial(n - 1)


This is partly based on the Python book and the Wikipedia Python article. Some examples are taken from the Python wiki.


QR Code
QR Code python (generated for current page)