Programming‎ > ‎Python‎ > ‎


1. Hello World
print "This line will be printed."
Python-3 print is a function. 
print("This line will be printed.")

2. Variables and Types
Numbers - integers and floating point numbers
myint = 7
myfloat = 7.0 
myfloat = float(7)
Strings - Defined either by single or double quote. Double quote will make it easy to include apostrophes.
mystring = 'hello' 
mystring = "hello"

3. Lists
Lists are very similar to arrays. They can contain any type of variable, and they can contain as many variables as you wish. Lists can also be iterated over in a very simple manner. 
mylist = []
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3

# prints out 1,2,3
for x in mylist:
    print x

Accessing an index which does not exist generates an exception (an error).
mylist = [1,2,3]

Traceback (most recent call last):
  File "", line 2, in <module>
IndexError: list index out of range

4. Basic Operators

Arithmetic Operators
number = 1 + 2 * 3 / 4.0
remainder = 11 % 3

Using two multiplication symbols makes a power relationship.
squared = 7 ** 2
cubed = 2 ** 3

Using Operators with Strings
helloworld = "hello" + " " + "world"

Python also supports multiplying strings to form a string with a repeating sequence:
lotsofhellos = "hello" * 10

Using Operators with Lists
Lists can be joined with the addition operators:
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers

Just as in strings, Python supports forming new lists with a repeating sequence using the multiplication operator:
print [1,2,3] * 3

5. String Formatting

# This prints out "Hello, John!"
name = "John"
print "Hello, %s!" % name

# This prints out "John is 23 years old."
name = "John"
age = 23
print "%s is %d years old." % (name, age)

# This prints out: A list: [1, 2, 3]
mylist = [1,2,3]
print "A list: %s" % mylist

%s - String (or any object with a string representation, like numbers)
%d - Integers
%f - Floating point numbers
%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X - Integers in hex representation (lowercase/uppercase)

6. Basic String Operations

astring = "Hello world!" # A String
print len(astring) # prints 12
print astring.index("o") # prints 4, index starts from 0
print astring.count("l") # counts and prints no of 'l'
print astring[3:7] # prints from 3rd character to 6th character, -3 will take it from end
print astring.upper() #convert to uppercase
print astring.lower() #conver to lowercase
print astring.startswith("Hello") # returns True , This is used to determine whether the string starts with something or ends with something
print astring.endswith("asdfasdfasdf") # returns False
afewwords = astring.split(" ") # Splits into ["Hello", "World!"]

7. Conditions
Python uses boolean variables True or False to evaluate conditions. 
x = 2
print x == 2 # prints out True , not equals is "!="
print x == 3 # prints out False
print x < 3  # prints out True

name = "John"
age = 23
if name == "John" and age == 23:
    print "Your name is John, and you are also 23 years old."

if name == "John" or name == "Rick":
    print "Your name is either John or Rick."

The "in" operator
The "in" operator could be used to check if a specified object exists within an iterable object container, such as a list:
if name in ["John", "Rick"]:
    print "Your name is either John or Rick."

Code blocks
Python uses indentation to define code blocks, instead of brackets. The standard Python indentation is 4 spaces, although tabs and any other space size will work, as long as it is consistent. Notice that code blocks do not need any termination.

Here is an example for using Python's "if" statement using code blocks:

if <statement is true>:
    <do something>
elif <another statement is true>: # else if
    <do something else>
    <do another thing>

A statement is evaulated as true if one of the following is correct: 1. The "True" boolean variable is given, or calculated using an expression, such as an arithmetic comparison. 2. An object which is not considered "empty" is passed.

Here are some examples for objects which are considered as empty: 1. An empty string: "" 2. An empty list: [] 3. The number zero: 0 4. The false boolean variable: False

The 'is' operator
Unlike the double equals operator "==", the "is" operator does not match the values of the variables, but the instances themselves. For example:

x = [1,2,3]
y = [1,2,3]
print x == y # Prints out True
print x is y # Prints out False

The "not" operator
Using "not" before a boolean expression inverts it:

print not False # Prints out True
print (not False) == (False) # Prints out False

8. Loops

The "for" loop
For loops iterate over a given sequence. Here is an example:

primes = [2, 3, 5, 7]
for prime in primes:
    print prime

For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference between range and xrange is that the range function returns a new list with numbers of that specified range, whereas xrange returns an iterator, which is more efficient. (Python 3 uses the range function, which acts like xrange). Note that the xrange function is zero based.

# Prints out the numbers 0,1,2,3,4
for x in xrange(5): # or range(5)
    print x

# Prints out 3,4,5
for x in xrange(3, 6): # or range(3, 6)
    print x

# Prints out 3,5,7
for x in xrange(3, 8, 2): # or range(3, 8, 2) 2 is step here
    print x

"while" loops
While loops repeat as long as a certain boolean condition is met. For example:

# Prints out 0,1,2,3,4

count = 0
while count < 5:
    print count
    count += 1  # This is the same as count = count + 1

"break" and "continue" statements
break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the "for" or "while" statement. A few examples:

# Prints out 0,1,2,3,4

count = 0
while True:
    print count
    count += 1
    if count >= 5:

# Prints out only odd numbers - 1,3,5,7,9
for x in xrange(10):
    # Check if x is even
    if x % 2 == 0:
    print x

9. Functions

What are Functions?
Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also functions are a key way to define interfaces so programmers can share their code.

How do you write functions in Python?
As we have seen on previous tutorials, Python makes use of blocks.

A block is a area of code of written in the format of:

    1st block line 
    2nd block line 

Where a block line is more Python code (even another block), and the block head is of the following format: block_keyword block_name(argument1,argument2, ...) Block keywords you already know are "if", "for", and "while".

Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. For example:

def my_function():
    print "Hello From My Function!"

Functions may also receive arguments (variables passed from the caller to the function). For example:

def my_function_with_args(username, greeting):
    print "Hello, %s , From My Function!, I wish you %s"%(username, greeting)

Functions may return a value to the caller, using the keyword- 'return' . For example:

def sum_two_numbers(a, b):
    return a + b

How do you call functions in Python?
Simply write the function's name followed by (), placing any required arguments within the brackets. For example, lets call the functions written above (in the previous example):

# print a simple greeting 

#prints - "Hello, John Doe, From My Function!, I wish you a great year!"
my_function_with_args("John Doe", "a great year!")

# after this line x will hold the value 3!
x = sum_two_numbers(1,2)

10. Classes and Objects

Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes. Classes are essentially a template to create your objects.

A very basic class would look something like this:

class MyClass:
    variable = "blah"

    def function(self):
        print "This is a message inside the class."

We'll explain why you have to include that "self" as a parameter a little bit later. First, to assign the above class(template) to an object you would do the following:

myobjectx = MyClass()

Now the variable "myobjectx" holds an object of the class "MyClass" that contains the variable and the function defined within the class called "MyClass".

Accessing Object Variables
To access the variable inside of the newly created object "MyObject" you would do the following:


So for instance the below would output the string "blah":

print myobjectx.variable

You can create multiple different objects that are of the same class(have the same variables and functions defined). However, each object contains independent copies of the variables defined in the class. For instance, if we were to define another object with the "MyClass" class and then change the string in the variable above:

myobjecty = MyClass()
myobjecty.variable = "yackity"

Then print out both values:

print myobjectx.variable   # This would print "blah".
print myobjecty.variable   # This would print "yackity".

Accessing Object Functions
To access a function inside of an object you use notation similar to accessing a variable:


The above would print out the message, "This is a message inside the class."

11. Dictionaries

A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it.

For example, a database of phone numbers could be stored using a dictionary like this:

phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781

Alternatively, a dictionary can be initialized with the same values in the following notation:

phonebook = {
    "John" : 938477566,
    "Jack" : 938377264,
    "Jill" : 947662781

Iterating over dictionaries
Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of the values stored in it. To iterate over key value pairs, use the following syntax:

for name, number in phonebook.iteritems():
    print "Phone number of %s is %d" % (name, number)

Removing a value
To remove a specified index, use either one of the following notations:

del phonebook["John"]

12. Modules and Packages

Modules in Python are simply Python files with the .py extension, which implement a set of functions. Modules are imported from other modules using the import command.

To import a module, we use the import command. Check out the full list of built-in modules in the Python standard library at 

The first time a module is loaded into a running Python script, it is initialized by executing the code in the module once. If another module in your code imports the same module again, it will not be loaded twice but once only - so local variables inside the module act as a "singleton" - they are initialized only once.

If we want to import the module urllib, which enables us to create read data from URLs, we simply import the module:

# import the library
import urllib

# use it

Exploring built-in modules
Two very important functions come in handy when exploring modules in Python - the dir and help functions.

We can look for which functions are implemented in each module by using the dir function:

>>> import urllib
>>> dir(urllib)
['ContentTooShortError', 'FancyURLopener', 'MAXFTPCACHE', 'URLopener', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', '_ftperrors', '_get_proxies', '_get_proxy_settings', '_have_ssl', '_hexdig', '_hextochr', '_hostprog', '_is_unicode', '_localhost', '_noheaders', '_nportprog', '_passwdprog', '_portprog', '_queryprog', '_safe_map', '_safe_quoters', '_tagprog', '_thishost', '_typeprog', '_urlopener', '_userprog', '_valueprog', 'addbase', 'addclosehook', 'addinfo', 'addinfourl', 'always_safe', 'basejoin', 'c', 'ftpcache', 'ftperrors', 'ftpwrapper', 'getproxies', 'getproxies_environment', 'getproxies_macosx_sysconf', 'i', 'localhost', 'main', 'noheaders', 'os', 'pathname2url', 'proxy_bypass', 'proxy_bypass_environment', 'proxy_bypass_macosx_sysconf', 'quote', 'quote_plus', 'reporthook', 'socket', 'splitattr', 'splithost', 'splitnport', 'splitpasswd', 'splitport', 'splitquery', 'splittag', 'splittype', 'splituser', 'splitvalue', 'ssl', 'string', 'sys', 'test', 'test1', 'thishost', 'time', 'toBytes', 'unquote', 'unquote_plus', 'unwrap', 'url2pathname', 'urlcleanup', 'urlencode', 'urlopen', 'urlretrieve']

When we find the function in the module we want to use, we can read about it more using the help function, inside the Python interpreter:


Writing modules
Writing Python modules is very simple. To create a module of your own, simply create a new .py file with the module name, and then import it using the Python file name (without the .py extension) using the import command.

Writing packages
Packages are namespaces which contain multiple packages and modules themselves. They are simply directories, but with a twist.

Each package in Python is a directory which MUST contain a special file called This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.

If we create a directory called foo, which marks the package name, we can then create a module inside that package called bar. We also must not forget to add the file inside the foo directory.

To use the module bar, we can import it in two ways:

from foo import bar
Execute Code
In the first method, we must use the foo prefix whenever we access the module bar. In the second method, we don't, because we import the module to our module's namespace.

The file can also decide which modules the package exports as the API, while keeping other modules internal, by overriding the __all__ variable, like so:

__all__ = ["bar"]