Python Operator – Types of Operators in Python

Being a high level language where it can fit into most of the system it has the capability to handle the all data types.To handle this data the operators are categorized into below 7 categories .

  • Python Arithmetic Operator
  • Python Relational Operator
  • Python Assignment Operator
  • Python Logical Operator
  • Python Membership Operator
  • Python Identity Operator
  • Python Bitwise Operator

Python Arithmetic Operator

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.

+Add two operands or unary plusx + y
Subtract right operand from the left or unary minusx – y
*Multiply two operandsx * y
/Divide left operand by the right one (always results into float)x / y
%Modulus – remainder of the division of left operand by the rightx % y (remainder of x/y)
//Floor division – division that results into whole number adjusted to the left in the number linex // y
**Exponent – left operand raised to the power of rightx**y (x to the power y)

Python Relational Operator

Relational operators are used to compare values. It either returns True or False according to the condition.

>Greater that – True if left operand is greater than the rightx > y
<Less that – True if left operand is less than the rightx < y
==Equal to – True if both operands are equalx == y
!=Not equal to – True if operands are not equalx != y
>=Greater than or equal to – True if left operand is greater than or equal to the rightx >= y
<=Less than or equal to – True if left operand is less than or equal to the rightx <= y

Python Assignment Operator

Assignment operators are used in Python to assign values to variables.

a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.

There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5.

OperatorExampleEquivatent to
=x = 5x = 5
+=x += 5x = x + 5
-=x -= 5x = x – 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
%=x %= 5x = x % 5
//=x //= 5x = x // 5
**=x **= 5x = x ** 5
&=x &= 5x = x & 5
|=x |= 5x = x | 5
^=x ^= 5x = x ^ 5
>>=x >>= 5x = x >> 5
<<=x <<= 5x = x << 5

Python Logical Operator

Logical operators are the andornot operators.

andTrue if both the operands are truex and y
orTrue if either of the operands is truex or y
notTrue if operand is false (complements the operand)not x

Python Membership Operator

in and not in are the membership operators in Python. They are used to test whether a value or variable is found in a sequence (stringlisttupleset and dictionary).

In a dictionary we can only test for presence of key, not the value.

inTrue if value/variable is found in the sequence5 in x
not inTrue if value/variable is not found in the sequence5 not in x

Python Identity Operator

is and is not are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical.

isTrue if the operands are identical (refer to the same object)x is True
is notTrue if the operands are not identical (do not refer to the same object)x is not True

Python Bitwise Operator

Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

&Bitwise ANDx& y = 0 (0000 0000)
|Bitwise ORx | y = 14 (0000 1110)
~Bitwise NOT~x = -11 (1111 0101)
^Bitwise XORx ^ y = 14 (0000 1110)
>>Bitwise right shiftx>> 2 = 2 (0000 0010)
<<Bitwise left shiftx<< 2 = 40 (0010 1000)

Creating Virtual Environment in Python using Command Line Arguments

Installing packages using pip In virtualenv

This guide discusses how to install packages using pip and virtualenv. These are the lowest-level tools for managing Python packages and are recommended if higher-level tools do not suit your needs.


This doc uses the term package to refer to a Distribution Package which is different from a Import Package that which is used to import modules in your Python source code.

Installing pip

pip is the reference Python package manager. It’s used to install and update packages. You’ll need to make sure you have the latest version of pip installed.


The Python installers for Windows include pip. You should be able to access pip using:

py -m pip --version
pip 9.0.1 from c:\python36\lib\site-packages (Python 3.6.1)

You can make sure that pip is up-to-date by running:

py -m pip install --upgrade pip

Linux and macOS

Debian and most other distributions include a python-pip package, if you want to use the Linux distribution-provided versions of pip see Installing pip/setuptools/wheel with Linux Package Managers.

You can also install pip yourself to ensure you have the latest version. It’s recommended to use the system pip to bootstrap a user installation of pip:

python3 -m pip install --user --upgrade pip

Afterwards, you should have the newest pip installed in your user site:

python3 -m pip --version
pip 9.0.1 from $HOME/.local/lib/python3.6/site-packages (python 3.6)

Installing virtualenv

virtualenv is used to manage Python packages for different projects. Using virtualenv allows you to avoid installing Python packages globally which could break system tools or other projects. You can install virtualenv using pip.

On macOS and Linux:

python3 -m pip install --user virtualenv

On Windows:

py -m pip install --user virtualenv


If you are using Python 3.3 or newer the venv module is included in the Python standard library. This can also create and manage virtual environments, however, it only supports Python 3.

Creating a virtualenv

virtualenv allows you to manage separate package installations for different projects. It essentially allows you to create a “virtual” isolated Python installation and install packages into that virtual installation. When you switch projects, you can simply create a new virtual environment and not have to worry about breaking the packages installed in the other environments. It is always recommended to use a virtualenv while developing Python applications.

To create a virtual environment, go to your project’s directory and run virtualenv.

On macOS and Linux:

python3 -m virtualenv env

On Windows:

py -m virtualenv env

The second argument is the location to create the virtualenv. Generally, you can just create this in your project and call it env.

virtualenv will create a virtual Python installation in the env folder.


You should exclude your virtualenv directory from your version control system using .gitignore or similar.

Activating a virtualenv

Before you can start installing or using packages in your virtualenv you’ll need to activate it. Activating a virtualenv will put the virtualenv-specific python and pip executables into your shell’s PATH.

On macOS and Linux:

source env/bin/activate

On Windows:


You can confirm you’re in the virtualenv by checking the location of your Python interpreter, it should point to the env directory.

On macOS and Linux:

which python

On Windows:

where python

As long as your virtualenv is activated pip will install packages into that specific environment and you’ll be able to import and use packages in your Python application.

Leaving the virtualenv

If you want to switch projects or otherwise leave your virtualenv, simply run:


If you want to re-enter the virtualenv just follow the same instructions above about activating a virtualenv. There’s no need to re-create the virtualenv.

Installing packages

Now that you’re in your virtualenv you can install packages. Let’s install the excellent Requests library from the Python Package Index (PyPI):

pip install requests

pip should download requests and all of its dependencies and install them:

Collecting requests
  Using cached requests-2.18.4-py2.py3-none-any.whl
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Using cached chardet-3.0.4-py2.py3-none-any.whl
Collecting urllib3<1.23,>=1.21.1 (from requests)
  Using cached urllib3-1.22-py2.py3-none-any.whl
Collecting certifi>=2017.4.17 (from requests)
  Using cached certifi-2017.7.27.1-py2.py3-none-any.whl
Collecting idna<2.7,>=2.5 (from requests)
  Using cached idna-2.6-py2.py3-none-any.whl
Installing collected packages: chardet, urllib3, certifi, idna, requests
Successfully installed certifi-2017.7.27.1 chardet-3.0.4 idna-2.6 requests-2.18.4 urllib3-1.22

Installing specific versions

pip allows you to specify which version of a package to install using version specifiers. For example, to install a specific version of requests:

pip install requests==2.18.4

To install the latest 2.x release of requests:

pip install requests>=2.0.0,<3.0.0

To install pre-release versions of packages, use the --pre flag:

pip install --pre requests

Installing extras

Some packages have optional extras. You can tell pip to install these by specifying the extra in brackets:

pip install requests[security]

Installing from source

pip can install a package directly from source, for example:

cd google-auth
pip install .

Additionally, pip can install packages from source in development mode, meaning that changes to the source directory will immediately affect the installed package without needing to re-install:

pip install --editable .

Installing from version control systems

pip can install packages directly from their version control system. For example, you can install directly from a git repository:


For more information on supported version control systems and syntax, see pip’s documentation on VCS Support.

Installing from local archives

If you have a local copy of a Distribution Package’s archive (a zip, wheel, or tar file) you can install it directly with pip:

pip install requests-2.18.4.tar.gz

If you have a directory containing archives of multiple packages, you can tell pip to look for packages there and not to use the Python Package Index (PyPI) at all:

pip install --no-index --find-links=/local/dir/ requests

This is useful if you are installing packages on a system with limited connectivity or if you want to strictly control the origin of distribution packages.

Using other package indexes

If you want to download packages from a different index than the Python Package Index (PyPI), you can use the --index-url flag:

pip install --index-url SomeProject

If you want to allow packages from both the Python Package Index (PyPI) and a separate index, you can use the --extra-index-url flag instead:

pip install --extra-index-url SomeProject

Upgrading packages

pip can upgrade packages in-place using the --upgrade flag. For example, to install the latest version of requests and all of its dependencies:

pip install --upgrade requests

Using requirements files

Instead of installing packages individually, pip allows you to declare all dependencies in a Requirements File. For example you could create a requirements.txt file containing:


And tell pip to install all of the packages in this file using the -r flag:

pip install -r requirements.txt

Freezing dependencies

Pip can export a list of all installed packages and their versions using the freeze command:

pip freeze

Which will output a list of package specifiers such as:


This is useful for creating Requirements Files that can re-create the exact versions of all packages installed in an environment.

What is Lambda, Filter, Reduce,Map & List Comprehension,Set Comprehension in Python

Although we all know that in python def(): is used to create a function,We can use a def() as er our requirement and modify accordingly.Sometimes its necessary to create a one line function known as Lambda.Which can be created by just in demand situation where it can  behave like an normal definition. We can see the result: lambda, map() and filter() are still part of core Python. Only reduce() had to go it is moved into the module functools.

  • There is an equally powerful alternative to lambda, filter, map and reduce, i.e. list comprehension
  • List comprehension is more evident and easier to understand
  • Having both list comprehension and “Filter, map, reduce and lambda” is transgressing the Python motto “There should be one obvious way to solve a problem”


Some like it, others feels complicated lambda operator. The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce(). The lambda feature was added to Python due to the demand from Lisp programmers.

The general syntax of a lambda function is quite simple:

lambda argument_list: expression

The argument list consists of a comma separated list of arguments and the expression is an arithmetic expression using these arguments. You can assign the function to a variable to give it a name.

The following example of a lambda function returns the average of its two arguments:

xx=lambda y:y*5

The above example might look like a plaything for a mathematician. A formalism which turns an easy to comprehend issue into an abstract harder to grasp formalism. Above all, we could have had the same effect by just using the following conventional function definition:

def xx(y):
    return y*5

We can assure you that the advantages of this approach will be apparent, when you will have learnt to use the map() function.

Lambda with if condition

The map() Function

The lambda operator can be seen when it is used in combination with the map() function.The map() is a function which takes two arguments the first one is the function and second one on which it needs to map the function.

r = map(func, seq)

The first argument func is the name of a function and the second a sequence (e.g. a list) seq. map() applies the function func to all the elements of the sequence seq. Before Python3, map() used to return a list, where each element of the result list was the result of the function func applied on the corresponding element of the list or tuple “seq”. With Python 3, map() returns an iterator.

In the below example we are calculating the total travel cost.Our distance=[30,50,80,12,90,40,60,20] list contain the number of distances.We are calculating the distance by car and bike and storing inside the respective list.We are using the lambda for creating inline function.And by using map we are mapping the function over the list of n elements.

car=lambda x:x*4
bike=lambda x:x*2

The below lines of code are the generic way of python definition to create a function and do same thing

def calcostByCar():
for i in distance:
#Per kilomeater i am considering 4$ as traveliing cost
print("Cost by car :",costByCar)
def calcostByBike():
for i in distance:
#Per kilomeater i am considering 2$ as traveliing cost
print("Cost by bike :",costByBike)

Output of the above program is as below.
[120, 200, 320, 48, 360, 160, 240, 80]
[60, 100, 160, 24, 180, 80, 120, 40]


The function

filter(function, sequence)

offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function function returns True. i.e. an item will be produced by the iterator result of filter(function, sequence) if item is included in the sequence “sequence” and if function(item) returns True.

In other words: The function filter(f,l) needs a function f as its first argument. f has to return a Boolean value, i.e. either True or False. This function will be applied to every element of the list l. Only if f returns True will the element be produced by the iterator, which is the return value of filter(function, sequence).

In the following example, we filter out first the odd and then the even elements of the sequence of the first 11 Fibonacci numbers:

>>> fibonacci = [0,1,1,2,3,5,8,13,21,34,55]
>>> odd_numbers = list(filter(lambda x: x % 2, fibonacci))
>>> print(odd_numbers)
[1, 1, 3, 5, 13, 21, 55]
>>> even_numbers = list(filter(lambda x: x % 2 == 0, fibonacci))
>>> print(even_numbers)
[0, 2, 8, 34]
>>> # or alternatively:
>>> even_numbers = list(filter(lambda x: x % 2 -1, fibonacci))
>>> print(even_numbers)
[0, 2, 8, 34]

Reducing a List

As we mentioned in the introduction of this chapter of our tutorial. reduce() had been dropped from the core of Python when migrating to Python 3. Guido van Rossum hates reduce(), as we can learn from his statement in a posting, March 10, 2005, in

“So now reduce(). This is actually the one I’ve always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what’s actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it’s better to write out the accumulation loop explicitly.”

The function

reduce(func, seq)

continually applies the function func() to the sequence seq. It returns a single value.

If seq = [ s1, s2, s3, … , sn ], calling reduce(func, seq) works like this:

  • At first the first two elements of seq will be applied to func, i.e. func(s1,s2) The list on which reduce() works looks now like this: [ func(s1, s2), s3, … , sn ]
  • In the next step func will be applied on the previous result and the third element of the list, i.e. func(func(s1, s2),s3)
    The list looks like this now: [ func(func(s1, s2),s3), … , sn ]
  • Continue like this until just one element is left and return this element as the result of reduce()

If n is equal to 4 the previous explanation can be illustrated like this: Reduce

We want to illustrate this way of working of reduce() with a simple example. We have to import functools to be capable of using reduce:

>>> import functools
>>> functools.reduce(lambda x,y: x+y, [47,11,42,13])

The following diagram shows the intermediate steps of the calculation:

Reduce: Method of operating

Examples of reduce()

Determining the maximum of a list of numerical values by using reduce:

>>> from functools import reduce
>>> f = lambda a,b: a if (a > b) else b
>>> reduce(f, [47,11,42,102,13])

Calculating the sum of the numbers from 1 to 100:

>>> from functools import reduce
>>> reduce(lambda x, y: x+y, range(1,101))

It’s very simple to change the previous example to calculate the product (the factorial) from 1 to a number, but do not choose 100. We just have to turn the “+” operator into “*”:

>>> reduce(lambda x, y: x*y, range(1,49))

If you are into lottery, here are the chances to win a 6 out of 49 drawing:

>>> reduce(lambda x, y: x*y, range(44,50))/reduce(lambda x, y: x*y, range(1,7))

List Comprehension


alternative to map, filter, reduce and lambda We learned  “Lambda Operator, Filter, Reduce and Map” that Guido van Rossum prefers list comprehensions to constructs using map, filter, reduce and lambda. In this chapter we will cover the essentials about list comprehensions. List comprehensions were added with Python 2.0. Essentially, it is Python’s way of implementing a well-known notation for sets as used by mathematicians.
In mathematics the square numbers of the natural numbers are, for example, created by { x2 | x ∈ ℕ } or the set of complex integers { (x,y) | x ∈ ℤ ∧ y ∈ ℤ }.

List comprehension is an elegant way to define and create list in Python. These lists have often the qualities of sets, but are not in all cases sets.

List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce(). For most people the syntax of list comprehension is easier to be grasped.


In the chapter on lambda and map() we had designed a map() function to convert Celsius values into Fahrenheit and vice versa. It looks like this with list comprehension:

>>> Celsius = [39.2, 36.5, 37.3, 37.8]
>>> Fahrenheit = [ ((float(9)/5)*x + 32) for x in Celsius ]
>>> print Fahrenheit
[102.56, 97.700000000000003, 99.140000000000001, 100.03999999999999]

The following list comprehension creates the Pythagorean triples:

>>> [(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2 == z**2]
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]

Cross product of two sets:

>>> colours = [ "red", "green", "yellow", "blue" ]
>>> things = [ "house", "car", "tree" ]
>>> coloured_things = [ (x,y) for x in colours for y in things ]
>>> print coloured_things
[('red', 'house'), ('red', 'car'), ('red', 'tree'), ('green', 'house'), ('green', 'car'), ('green', 'tree'), ('yellow', 'house'), ('yellow', 'car'), ('yellow', 'tree'), ('blue', 'house'), ('blue', 'car'), ('blue', 'tree')]

Generator Comprehension

Generator comprehensions were introduced with Python 2.6. They are simply a generator expression with a parenthesis – round brackets – around it. Otherwise, the syntax and the way of working is like list comprehension, but a generator comprehension returns a generator instead of a list.

>>> x = (x **2 for x in range(20))
>>> print(x)
 at 0xb7307aa4>
>>> x = list(x)
>>> print(x)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]

A more Demanding Example

Calculation of the prime numbers between 1 and 100 using the sieve of Eratosthenes:

>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 100, i)]
>>> primes = [x for x in range(2, 100) if x not in noprimes]
>>> print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

We want to bring the previous example into more general form, so that we can calculate the list of prime numbers up to an arbitrary number n:

>>> from math import sqrt
>>> n = 100
>>> sqrt_n = int(sqrt(n))
>>> no_primes = [j for i in range(2,sqrt_n) for j in range(i*2, n, i)]

If we have a look at the content of no_primes, we can see that we have a problem. There are lots of double entries contained in this list:

>>> no_primes
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99]

The solution to this intolerable problem comes with the set comprehension, which we will cover in the next section.

Set Comprehension

A set comprehension is similar to a list comprehension, but returns a set and not a list. Syntactically, we use curly brackets instead of square brackets to create a set. Set comprehension is the right functionality to solve our problem from the previous subsection. We are able to create the set of non primes without doublets:

>>> from math import sqrt
>>> n = 100
>>> sqrt_n = int(sqrt(n))
>>> no_primes = {j for i in range(2,sqrt_n) for j in range(i*2, n, i)}
>>> no_primes
{4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99}
>>> primes = {i for i in range(n) if i not in no_primes}
>>> print(primes)
{0, 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}

Recursive Function to Calculate the Primes

The following Python script uses a recursive function to calculate the prime numbers. It incorporates the fact that it is enough to examine the multiples of the prime numbers up to the square root of n:

from math import sqrt
def primes(n):
    if n == 0:
        return []
    elif n == 1:
        return []
        p = primes(int(sqrt(n)))
        no_p = {j for i in p for j in xrange(i*2, n+1, i)}
        p = {x for x in xrange(2, n + 1) if x not in no_p}
    return p

for i in range(1,50):
    print i, primes(i) 

Installation of Python Version(2.7/3.*) in Windows

Installation of Pyhton Version(2.7/3.*) is very easy because of it GUI Installer.Which made the life simple for the programmer.For the installation of Pyhon we need to  follow the below steps.

If you are a beginner in python before choosing the version you can go through the post The Difference Between Pyhton 2.x and Python 3.x

Step 1:Download Python According to System Processor 

Depending on your system processor you have choose the appropriate exe file from the download page Link.

Step 2:Run the Package Installer & Setup the Python Executable Path

After downloading the python you need to install it in your system by double clicking it.During installation you need to setup few things without which you can face difficulties in future.

#Need to provide the installation path at the time of setup otherwise it will take the system default path.You have to create a folder named as PythonXX with post fix your version code. In my case i have created a folder Python37 for the python 3.7 version installation.As shown in the below image.

#Select Customize Installation.

#Add Pyhton 3.7 to PATH

#Check the options



Python Test Suite

#Give the Python37 Folder Location which you have created at first step.

Step 3:Open Command and Check the Installation

Open you command prompt and Type python -v in your command prompt .Now you can able to see the pyhton version installed in your system.If you don’t find the  pyton version installed in your system you might have skip some step from above please reinstall pyhton with above prerequisite or you can setup your python path manually as provided in the step #4.

Step 4:Setting Up Python Path in the environment variable.

Go to your my computer->Properties->Advance System Setting ->Go to advance Tab->Click on Environmental Variable .

You will find two section where you need to give your python installation location as shown in the image.

If you still find difficulties please comment below with your error code.And please do not forget to give your comment.

Difference Between Pyhton 2.X Vs 3.X

The key differences between Python 2.7.x and Python 3.x with examples

Many beginning Python users are wondering with which version of Python they should start their career. Our answer to this question is usually something along the lines “just go with the version your favorite tutorial was written in, and check out the differences later on.”But what if you are starting a new project and have the choice to pick? I would say there is currently no “right” or “wrong” as long as both Python 2.7.x and Python 3.x support the libraries that you are planning to use. However, it is worthwhile to have a look at the major differences between those two most popular versions of Python to avoid common pitfalls when writing the code for either one of them, or if you are planning to port your project.

The Key Differences are as below

  1. The __future__ module in python 2
  2. The print function
    1. Python 2
    2. Python 3
  3. Integer division
    1. Python 2
    2. Python 3
  4. Unicode
    1. Python 2
    2. Python 3
  5. xrange
    1. Python 2
    2. Python 3
    3. The __contains__ method for range objects in Python 3
      1. Note about the speed differences in Python 2 and 3
  6. Raising exceptions
    1. Python 2
    2. Python 3
  7. Handling exceptions
    1. Python 2
    2. Python 3
  8. The next() function and .next() method
    1. Python 2
    2. Python 3
  9. For-loop variables and the global namespace leak
    1. Python 2
    2. Python 3
  10. Comparing unorderable types
    1. Python 2
    2. Python 3
  11. Parsing user inputs via input()
    1. Python 2
    2. Python 3
  12. Returning iterable objects instead of lists
    1. Python 2
    2. Python 3
  13. Banker’s Rounding
    1. Python 2
    2. Python 3
  14. More articles about Python 2 and Python 3

1.The __future__ module

Python 3.x introduced some Python 2-incompatible keywords and features that can be imported via the in-built __future__ module in Python 2. It is recommended to use __future__ imports it if you are planning Python 3.x support for your code. For example, if we want Python 3.x’s integer division behavior in Python 2, we can import it via the folowing syntax.

from __future__ import division

More features that can be imported from the __future__ module are listed in the table below:

feature optional in mandatory in effect
nested_scopes 2.1.0b1 2.2 PEP 227: Statically Nested Scopes
generators 2.2.0a1 2.3 PEP 255: Simple Generators
division 2.2.0a2 3.0 PEP 238: Changing the Division Operator
absolute_import 2.5.0a1 3.0 PEP 328: Imports: Multi-Line and Absolute/Relative
with_statement 2.5.0a1 2.6 PEP 343: The “with” Statement
print_function 2.6.0a2 3.0 PEP 3105: Make print a function
unicode_literals 2.6.0a2 3.0 PEP 3112: Bytes literals in Python 3000

(Source: [](

from platform import python_version

2.The print function

This is an important change in the Pyhton from the 2 to 3, and the change in the print-syntax is probably the most widely known change, but still it is worth mentioning: Python 2’s print statement has been replaced by the print() function, meaning that we have to wrap the object that we want to print in parenthesis.

Python 2 doesn’t have a problem with additional parenthesis, but in contrast, Python 3 would raise a SyntaxError if we called the print function the Python 2-way without the parentheses.

Python 2

print 'Python', python_version()
print 'Hello, World!'
print('Hello, World!')
print "text", ; print 'print more text on the same line'
Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line

Python 3

print('Python', python_version())
print('Hello, World!')

print("some text,", end="")
print(' print more text on the same line')
Python 3.4.1
Hello, World!
some text, print more text on the same line
print 'Hello, World!'
  File "<ipython-input-3-139a7c5835bd>", line 1
    print 'Hello, World!'
SyntaxError: invalid syntax


Printing “Hello, World” above via Python 2 looked quite “normal”. However, if we have multiple objects inside the parantheses, we will create a tuple, since print is a “statement” in Python 2, not a function call.

print 'Python', python_version()
print('a', 'b')
print 'a', 'b'
Python 2.7.7
('a', 'b')
a b

3.Integer division

This change is particularly dangerous if you are porting code, or if you are executing Python 3 code in Python 2, since the change in integer-division behavior can often go unnoticed (it doesn’t raise a SyntaxError).
So, I still tend to use a float(3)/2 or 3/2.0 instead of a 3/2 in my Python 3 scripts to save the Python 2 guys some trouble (and vice versa, I recommend a from __future__ import division in your Python 2 scripts).

Python 2

print 'Python', python_version()
print '3 / 2 =', 3 / 2
print '3 // 2 =', 3 // 2
print '3 / 2.0 =', 3 / 2.0
print '3 // 2.0 =', 3 // 2.0
Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

Python 3

print('Python', python_version())
print('3 / 2 =', 3 / 2)
print('3 // 2 =', 3 // 2)
print('3 / 2.0 =', 3 / 2.0)
print('3 // 2.0 =', 3 // 2.0)
Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0


Python 2 has ASCII str() types, separate unicode(), but no byte type.

Now, in Python 3, we finally have Unicode (utf-8) strings, and 2 byte classes: byte and bytearrays.

Python 2

print 'Python', python_version()
Python 2.7.6
print type(unicode('this is like a python3 str type'))
<type 'unicode'>
print type(b'byte type does not exist')
<type 'str'>
print 'they are really' + b' the same'
they are really the same
print type(bytearray(b'bytearray oddly does exist though'))
<type 'bytearray'>

Python 3

print('Python', python_version())
print('strings are now utf-8 \u03BCnico\u0394é!')
Python 3.4.1
strings are now utf-8 μnicoΔé!
print('Python', python_version(), end="")
print(' has', type(b' bytes for storing data'))
Python 3.4.1 has <class 'bytes'>
print('and Python', python_version(), end="")
print(' also has', type(bytearray(b'bytearrays')))
and Python 3.4.1 also has <class 'bytearray'>
'note that we cannot add a string' + b'bytes for data'
TypeError                                 Traceback (most recent call last)

<ipython-input-13-d3e8942ccf81> in <module>()
----> 1 'note that we cannot add a string' + b'bytes for data'

TypeError: Can't convert 'bytes' object to str implicitly


The usage of xrange() is very popular in Python 2.x for creating an iterable object, e.g., in a for-loop or list/set-dictionary-comprehension.
The behavior was quite similar to a generator (i.e., “lazy evaluation”), but here the xrange-iterable is not exhaustible – meaning, you could iterate over it infinitely.

Thanks to its “lazy-evaluation”, the advantage of the regular range() is that xrange() is generally faster if you have to iterate over it only once (e.g., in a for-loop). However, in contrast to 1-time iterations, it is not recommended if you repeat the iteration multiple times, since the generation happens every time from scratch!

In Python 3, the range() was implemented like the xrange() function so that a dedicated xrange() function does not exist anymore (xrange() raises a NameError in Python 3).

import timeit

n = 10000
def test_range(n):
    return for i in range(n):

def test_xrange(n):
    for i in xrange(n):

Python 2

print 'Python', python_version()

print '\ntiming range()'
%timeit test_range(n)

print '\n\ntiming xrange()'
%timeit test_xrange(n)
Python 2.7.6

timing range()
1000 loops, best of 3: 433 µs per loop

timing xrange()
1000 loops, best of 3: 350 µs per loop

Python 3

print('Python', python_version())

print('\ntiming range()')
%timeit test_range(n)
Python 3.4.1

timing range()
1000 loops, best of 3: 520 µs per loop
NameError                                 Traceback (most recent call last)

<ipython-input-5-5d8f9b79ea70> in <module>()
----> 1 print(xrange(10))

NameError: name 'xrange' is not defined

6.The __contains__ method for range objects in Python 3

Another thing worth mentioning is that range got a “new” __contains__ method in Python 3.x (thanks to Yuchen Ying, who pointed this out). The __contains__ method can speedup “look-ups” in Python 3.x range significantly for integer and Boolean types.

x = 10000000
def val_in_range(x, val):
    return val in range(x)
def val_in_xrange(x, val):
    return val in xrange(x)
print('Python', python_version())
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_range(x, x/2)
%timeit val_in_range(x, x//2)
Python 3.4.1
1 loops, best of 3: 742 ms per loop
1000000 loops, best of 3: 1.19 µs per loop

Based on the timeit results above, you see that the execution for the “look up” was about 60,000 faster when it was of an integer type rather than a float. However, since Python 2.x’s range or xrange doesn’t have a __contains__ method, the “look-up speed” wouldn’t be that much different for integers or floats:

print 'Python', python_version()
assert(val_in_xrange(x, x/2.0) == True)
assert(val_in_xrange(x, x/2) == True)
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_xrange(x, x/2.0)
%timeit val_in_xrange(x, x/2)
%timeit val_in_range(x, x/2.0)
%timeit val_in_range(x, x/2)
Python 2.7.7
1 loops, best of 3: 285 ms per loop
1 loops, best of 3: 179 ms per loop
1 loops, best of 3: 658 ms per loop
1 loops, best of 3: 556 ms per loop

Below the “proofs” that the __contain__ method wasn’t added to Python 2.x yet:

print('Python', python_version())
Python 3.4.1

<slot wrapper '__contains__' of 'range' objects>
print 'Python', python_version()
Python 2.7.7

AttributeError                            Traceback (most recent call last)

<ipython-input-7-05327350dafb> in <module>()
      1 print 'Python', python_version()
----> 2 range.__contains__

AttributeError: 'builtin_function_or_method' object has no attribute '__contains__'
print 'Python', python_version()
Python 2.7.7

AttributeError                            Traceback (most recent call last)

<ipython-input-8-7d1a71bfee8e> in <module>()
      1 print 'Python', python_version()
----> 2 xrange.__contains__

AttributeError: type object 'xrange' has no attribute '__contains__'

Note about the speed differences in Python 2 and 3

Some people pointed out the speed difference between Python 3’s range() and Python2’s xrange(). Since they are implemented the same way one would expect the same speed. However the difference here just comes from the fact that Python 3 generally tends to run slower than Python 2.

def test_while():
    i = 0
    while i < 20000:
        i += 1
print('Python', python_version())
%timeit test_while()
Python 3.4.1
100 loops, best of 3: 2.68 ms per loop
print 'Python', python_version()
%timeit test_while()
Python 2.7.6
1000 loops, best of 3: 1.72 ms per loop

7.Raising exceptions

Where Python 2 accepts both notations, the ‘old’ and the ‘new’ syntax, Python 3 chokes (and raises a SyntaxError in turn) if we don’t enclose the exception argument in parentheses:

Python 2

print 'Python', python_version()
Python 2.7.6
raise IOError, "file error"
IOError                                   Traceback (most recent call last)

<ipython-input-8-25f049caebb0> in <module>()
----> 1 raise IOError, "file error"

IOError: file error
raise IOError("file error")
IOError                                   Traceback (most recent call last)

<ipython-input-9-6f1c43f525b2> in <module>()
----> 1 raise IOError("file error")

IOError: file error

Python 3

print('Python', python_version())
Python 3.4.1
raise IOError, "file error"
  File "<ipython-input-10-25f049caebb0>", line 1
    raise IOError, "file error"
SyntaxError: invalid syntax

The proper way to raise an exception in Python 3:

print('Python', python_version())
raise IOError("file error")
Python 3.4.1

OSError                                   Traceback (most recent call last)

<ipython-input-11-c350544d15da> in <module>()
      1 print('Python', python_version())
----> 2 raise IOError("file error")

OSError: file error

8.Handling exceptions

Also the handling of exceptions has slightly changed in Python 3. In Python 3 we have to use the “as” keyword now

Python 2

print 'Python', python_version()
except NameError, err:
    print err, '--> our error message'
Python 2.7.6
name 'let_us_cause_a_NameError' is not defined --> our error message

Python 3

print('Python', python_version())
except NameError as err:
    print(err, '--> our error message')
Python 3.4.1
name 'let_us_cause_a_NameError' is not defined --> our error message

9.The next() function and .next() method

Since next() (.next()) is such a commonly used function (method), this is another syntax change (or rather change in implementation) that is worth mentioning: where you can use both the function and method syntax in Python 2.7.5, the next() function is all that remains in Python 3 (calling the .next() method raises an AttributeError).

Python 2

print 'Python', python_version()

my_generator = (letter for letter in 'abcdefg')

Python 2.7.6


Python 3

print('Python', python_version())

my_generator = (letter for letter in 'abcdefg')

Python 3.4.1

AttributeError                            Traceback (most recent call last)

<ipython-input-14-125f388bb61b> in <module>()
----> 1

AttributeError: 'generator' object has no attribute 'next'

10.For-loop variables and the global namespace leak

Good news is: In Python 3.x for-loop variables don’t leak into the global namespace anymore!

This goes back to a change that was made in Python 3.x and is described in What’s New In Python 3.0 as follows:

“List comprehensions no longer support the syntactic form [... for var in item1, item2, ...]. Use [... for var in (item1, item2, ...)] instead. Also note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a list() constructor, and in particular the loop control variables are no longer leaked into the surrounding scope.”

Python 2

print 'Python', python_version()

i = 1
print 'before: i =', i

print 'comprehension: ', [i for i in range(5)]

print 'after: i =', i
Python 2.7.6
before: i = 1
comprehension:  [0, 1, 2, 3, 4]
after: i = 4

Python 3

print('Python', python_version())

i = 1
print('before: i =', i)

print('comprehension:', [i for i in range(5)])

print('after: i =', i)
Python 3.4.1
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 1

11.Comparing unorderable types

Another nice change in Python 3 is that a TypeError is raised as warning if we try to compare unorderable types.

Python 2

print 'Python', python_version()
print "[1, 2] > 'foo' = ", [1, 2] > 'foo'
print "(1, 2) > 'foo' = ", (1, 2) > 'foo'
print "[1, 2] > (1, 2) = ", [1, 2] > (1, 2)
Python 2.7.6
[1, 2] > 'foo' =  False
(1, 2) > 'foo' =  True
[1, 2] > (1, 2) =  False

Python 3

print('Python', python_version())
print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))
Python 3.4.1

TypeError                                 Traceback (most recent call last)

<ipython-input-16-a9031729f4a0> in <module>()
      1 print('Python', python_version())
----> 2 print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
      3 print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
      4 print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))

TypeError: unorderable types: list() > str()

12.Parsing user inputs via input()

Fortunately, the input() function was fixed in Python 3 so that it always stores the user inputs as str objects. In order to avoid the dangerous behavior in Python 2 to read in other types than strings, we have to use raw_input() instead.

Python 2

Python 2.7.6
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> my_input = input('enter a number: ')

enter a number: 123

>>> type(my_input)
<type 'int'>

>>> my_input = raw_input('enter a number: ')

enter a number: 123

>>> type(my_input)
<type 'str'>

Python 3

Python 3.4.1
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> my_input = input('enter a number: ')

enter a number: 123

>>> type(my_input)
<class 'str'>

13.Returning iterable objects instead of lists

As we have already seen in the xrange section, some functions and methods return iterable objects in Python 3 now – instead of lists in Python 2.

Since we usually iterate over those only once anyway, I think this change makes a lot of sense to save memory. However, it is also possible – in contrast to generators – to iterate over those multiple times if needed, it is only not so efficient.

And for those cases where we really need the list-objects, we can simply convert the iterable object into a list via the list() function.

Python 2

print 'Python', python_version()

print range(3)
print type(range(3))
Python 2.7.6
[0, 1, 2]
<type 'list'>

Python 3

print('Python', python_version())

Python 3.4.1
range(0, 3)
<class 'range'>
[0, 1, 2]

Some more commonly used functions and methods that don’t return lists anymore in Python 3:

  • zip()
  • map()
  • filter()
  • dictionary’s .keys() method
  • dictionary’s .values() method
  • dictionary’s .items() method

14.Banker’s Rounding

Python 3 adopted the now standard way of rounding decimals when it results in a tie (.5) at the last significant digits. Now, in Python 3, decimals are rounded to the nearest even number. Although it’s an inconvenience for code portability, it’s supposedly a better way of rounding compared to rounding up as it avoids the bias towards large numbers. For more information, see the excellent Wikipedia articles and paragraphs:


Python 2

print 'Python', python_version()
Python 2.7.12

Python 3

print('Python', python_version())
Python 3.5.1

Features of Python Programming Language

As being programmer we always play with the programming languages.To work with any programming language we need to know the thatcher are available in a particular programming language.In this below post we will discuss the features of that language.In this Features of Python Programming Language post we will discuss in details .
If we compare with other language Python is a simple and minimalistic language. Reading a good Python program feels almost like reading English (but very strict English!). This pseudo-code nature of Python is one of its greatest strengths. It allows you to concentrate on the solution to the problem rather than the syntax i.e. the language itself.
Easy to Learn
As you will see, Python is extremely easy to get started with. Python has an extraordinarily simple syntax as already mentioned.For an armature it will be a very easy stuff to learn it quickly,because of its English like keywords.
Free and Open Source
Everyone needs an free solution for the organization.Pyhton is being a free and powerful solution  which is an example of a FLOSS (Free/Libre and Open Source Software). In simple terms, you can freely distribute copies of this software, read the software’s source code, make changes to it, use pieces of it in new free programs, and that you know you can do these things. FLOSS is based on the concept of a community which shares knowledge. This is one of the reasons why Python is so good – it has been created and improved by a community who just want to see a better Python.
High-level Language
When you write programs in Python, you never need to bother about low-level details such as managing the memory used by your program.Unlike any other language python is not an complex stuff for managing the memory.Its inbuilt mechanism can able manage the memory by itself.
Due to its open-source nature, Python has been ported (i.e. changed to make it work on) to many many platforms. All your Python programs will work on any of these platforms without requiring any changes at all. However, you must be careful enough to avoid any system-dependent features.

You can use Python on Linux, Windows, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE and PocketPC !

This requires a little explanation.

A program written in a compiled language like C or C++ is translated from the source language i.e. C/C++ into a language spoken by your computer (binary code i.e. 0s and 1s) using a compiler with various flags and options. When you run the program, the linker/loader software just stores the binary code in the computer’s memory and starts executing from the first instruction in the program.

When you use an interpreted language like Python, there is no separate compilation and execution steps. You just run the program from the source code. Internally, Python converts the source code into an intermediate form called bytecodes and then translates this into the native language of your specific computer and then runs it. All this makes using Python so much easier. You just run your programs – you never have to worry about linking and loading with libraries, etc. They are also more portable this way because you can just copy your Python program into another system of any kind and it just works!

Object Oriented
Python supports procedure-oriented programming as well as object-oriented programming. In procedure-oriented languages, the program is built around procedures or functions which are nothing but reusable pieces of programs. In object-oriented languages, the program is built around objects which combine data and functionality. Python has a very powerful but simple way of doing object-oriented programming, especially, when compared to languages like C++ or Java.
It will support the other language bindings.If you need a critical piece of code to run very fast, you can achieve this by writing that piece of code in C, and then combine that with your Python program.
Cross language support feature is providing more power to python.You can embed Python within your C/C++ program to give scripting capabilities for your program’s users.
Extensive Libraries
The Python Standard Library is huge indeed. It can help you do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, ftp, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI(graphical user interfaces) using Tk, and also other system-dependent stuff. Remember, all this is always available wherever Python is installed. This is called the “batteries included” philosophy of Python.

Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library.



Python is indeed an exciting and powerful language. It has the right combination of performance and features that makes writing programs in Python both fun and easy.

How to Handle XML Files in Python



  • Xml (eXtensible Markup Language) is a markup language.
  • XML is designed to store and transport data.
  • Xml was released in late 90’s. it was created to provide an easy to use and store self-describing data.
  • XML became a W3C Recommendation on February 10, 1998.
  • XML is not a replacement for HTML.
  • XML is designed to be self-descriptive.
  • XML is designed to carry data, not to display data.
  • XML tags are not predefined. You must define your own tags.
  • XML is platform independent and language independent.

Sample XML File
























Python Module (xml.etree.ElementTree)


This method will take the xml file as input  will parse to the python friendly tree.


This will return us the roots of the tree element.


This method will return us the attribute of an particular root element.

import xml.etree.ElementTree as ETT
tree = ETT.parse('ConData.xml')
root = tree.getroot()
for i in root:
    for j in i:

# for country in root.findall('country'):
#     rank = country.find('rank').text
#     rank = country.find('rank')
#     name = country.get('name')
#     print (name, rank)

Pyhton Code to Get Text Data From Pdf File by fetching form URL or Form Local Drive

In this post we will explain how to fetch the text data from the pdf file using Pyhton Code. To Get Text Data From Pdf You need to in install the flowing python library for data read form the pdf document.


This library will help you to download data file or pdf from the internet.By using this library we can download file from the http sites .

To install url library use this below command to get the data form the web.

pip install urllib

pip install urllib2

pip install urllib3

import urllib

urllib.urlretrieve(‘’, ‘data.pdf’)


This library will help you to read the pdf and extract data

import PyPDF2
pdfFileObj = open('data.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
print pdfReader.numPages
pageObj = pdfReader.getPage(0)
print pageObj.extractText()

Looping in Python

Single Statement Suites

If the suite of an if clause consists only of a single line, it may go on the same line as the header statement.

Here is an example of a one-line if clause −

Live Demo


var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"

When the above code is executed, it produces the following result −

Value of expression is 100
Good bye!

In general, statements are executed sequentially − The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.

Programming languages provide various control structures that allow more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement −

Loop Architecture

Python programming language provides the following types of loops to handle looping requirements.

S.No. Loop Type & Description
1 while loopRepeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
2 for loopExecutes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
3 nested loopsYou can use one or more loop inside any another while, or for loop.

Loop Control Statements

The Loop control statements change the execution from its normal sequence. When the execution leaves a scope, all automatic objects that were created in that scope are destroyed.

Python supports the following control statements.

S.No. Control Statement & Description
1 break statementTerminates the loop statement and transfers execution to the statement immediately following the loop.
2 continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
3 pass statementThe pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

Let us go through the loop control statements briefly.

Iterator and Generator

Iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation. In Python, an iterator object implements two methods, iter() and next().

String, List or Tuple objects can be used to create an Iterator.

list = [1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object can be traversed using regular for statement
for x in it:
   print (x, end=" ")
or using next() function
while True:
      print (next(it))
   except StopIteration:
      sys.exit() #you have to import sys module for this

A generator is a function that produces or yields a sequence of values using yield method.

When a generator function is called, it returns a generator object without even beginning execution of the function. When the next() method is called for the first time, the function starts executing until it reaches the yield statement, which returns the yielded value. The yield keeps track i.e. remembers the last execution and the second next() call continues from previous value.


The following example defines a generator, which generates an iterator for all the Fibonacci numbers.

import sys
def fibonacci(n): #generator function
   a, b, counter = 0, 1, 0
   while True:
      if (counter > n): 
      yield a
      a, b = b, a + b
      counter += 1
f = fibonacci(5) #f is iterator object

while True:
      print (next(f), end=" ")
   except StopIteration:




Python Variable Declaration Rules and Syntax

Variable and Value

  • A variable is a memory location where a programmer can store a value. Example : roll_no, amount, name etc.
  • Value is either string, numeric etc. Example : “Sara”, 120, 25.36
  • Variables are created when first assigned.
  • Variables must be assigned before being referenced.
  • The value stored in a variable can be accessed or updated later.
  • No declaration required
  • The type (string, int, float etc.) of the variable is determined by Python
  • The interpreter allocates memory on the basis of the data type of a variable.

Python Variable Name Rules

  • Must begin with a letter (a – z, A – B) or underscore (_)
  • Other characters can be letters, numbers or _
  • Case Sensitive
  • Can be any (reasonable) length
  • There are some reserved words which you cannot use as a variable name because Python uses them for other things.

Good Variable Name

  • Choose meaningful name instead of short name. roll_no is better than rn.
  • Maintain the length of a variable name. Roll_no_of_a-student is too long?
  • Be consistent; roll_no or or RollNo
  • Begin a variable name with an underscore(_) character for a special case.

Variable assignment

We use the assignment operator (=) to assign values to a variable. Any type of value can be assigned to any valid variable.

a = 5
b = 3.2
c = "Hello"

Here, we have three assignment statements. 5 is an integer assigned to the variable a.

Similarly, 3.2 is a floating point number and "Hello" is a string (sequence of characters) assigned to the variables b and c respectively.

Multiple assignments

In Python, multiple assignments can be made in a single statement as follows:

a, b, c = 5, 3.2, "Hello"

If we want to assign the same value to multiple variables at once, we can do this as

x = y = z = "same"

This assigns the “same” string to all the three variables.

If  you have any further clarification on this topic please give comment bellow Python Variable Declaration Rules and Syntax