Difference Between Python 2 and 3
Difference Between Python 2 and 3
Python 2 Python 3
print type(Unicode(“Hello”))
print (‘\u03BCnico\u394e!’)
>> <type ‘unicode’>
>> µnico∆e!
print type(b’Hello’)
print(type(b’hello’))
>> <type ‘str’>
>> <class ‘bytes’>
3. Unicode
print ‘hello’ + b’ world’
print(‘hello’ + b’ world’))
>>hello world
>> TypeError
print type(bytearray(b’hello
print(type(bytearray(b’hello’)))
world’))
>> <class ‘bytearray’>
>> <type ‘bytearray’>
try:
try:
print 4/0
print(4/0)
except ZeroDivisionError, err:
except ZeroDivisionError as err:
print “can’t divide by zero”
6. Handling print(“can’t divide by zero”)
print “error – “ + err
exception print(“error –“ + str(err))
output:
output:
can’t divide by zero
can’t divide by zero
error – integer division or
error – division by zero
modulo by zero
i=1 i=1
print ‘before: i = ‘, i print(‘before :i =’, i)
print ‘loop:’,[i for i in range(5)] print(‘loop:’ [i for i in range(5)])
7. Leak of for-loop
print ‘after:i = ‘, i print(‘after: i = ‘, i)
variables in global
Output: Output:
namespace
before: i =1 before: i = 1
loop: [0,1,2,3,4] loop: [0,1,2,3,4]
after: i = 4 after: i = 1
8. .next() method have next() function and Have only next() function.
.next() method for iterate next list1 = [4, 43, 34, 32]
element. iterator = iter(list1)
list1 = [4, 43, 34, 32] print (next(iterator))
iterator = iter(list1) print (next(iterator))
print iterator.next() print (next(iterator))
print next(iterator)
print iterator.next() Output:
Output: 4
4 43
43 34
34
1. Integer Division:-
In python 2 if we perform division on two integers then the output will be an integer too.
But in python 3, output will be accurate, so the result can be in float too. Still want the
result in integer, then you can use print(9//2) it return an integer result.
2. Print Function:-
In python 2 parenthesis aren’t compulsory to use we can print anything without using
parenthesis but in Python 3 it is compulsory to use parenthesis otherwise it will raise error.
3. Unicode:-
Python 2 has ASCII str() Types, separate Unicode but it doesn’t have byte type.
But in Python 3 we have Unicode (utf-8: 8 means it uses 8-bit block to represent a
character) strings and also 2 byte classes that are bytearray and byte.
Python 2 treats string and bytes as same, so we can also concatenate them. But in Python
3 we can’t concatenate a byte array with strings, because both are different for python 3.
4. xrange function:-
python 2 has two handy function for creating a range of integers that is used in for loop,
these are range and xrange. They both provide a way to generate a list of integers. So for
the most part, xrange and range are the exact same in terms of functionality. The only
difference is that range returns a Python List object and xrange returns
an xrange object. range function creates an array of integers, so it will take much memory
if we create a range of millions, which can result MemoryError and crash your program.
So xrange is the function to use if you’ve a really memory sensitive system such as cell
phone.
But in python 3 there is no xrange function, the range function will work as xrange in
python 2.
Example:
#program in python 3
for i in range(1,10):
print(i)
#program in python 2
for i in xrange(1,10):
print i
Output
1
2
3
4
5
6
7
8
9
5. Raising exception:-
as we’ve seen the difference between print function, raising an exception will follow the
same syntax.
In python 2, its raise IOError, “file not found”
In python 3, its raise IOError(“file not found”)
6. Handling exception:-
there is a minor change in syntax, we’ve to use as keyword in python 3.
In python 2, its except IOError, err:
In python 3, its except IOError as err:
7. Leak of for-loop variables in global namespace:-
In python 2 there was a problem that value of a global variable had changed while using
that variable in for-loop.
But in Python 3, for loop variables don’t leak into the global namespace anymore!
8. .next() method:-
Python have .next() method and next() function to fetch the next element of an iterator.
But in python 3 .next() method is no more. We have to use only next() function to iterate the
next element of iterator.
9.input() method:-
python 2 have input() and raw_input() methods for taking input. The difference between
them raw_input() returns a string, and input() tries to run the input as a python expression.
Mostly all we want the string as input then we convert it into any datatype as we want.
In python 3 there is no raw_input() method. The raw_input() method is replaced by input()
in python 3. If you still want to use the input() method like in python 2 then we can use
eval() method.
eval(input(“enter something:”))
it will work as same as input() in python 2.
There are many other differences between python 2 and python 3 like
10. The __future__ Module:-
as we know there are many things that python 3 supports but python 2 don’t. if you’re
planning python 3 support for your code then use __future__ module.
Let’s say we want python 3’s integer division behavior in our python 2 program then our
program will look like
from __future__ import division
print 9/2
output:
4.5
without __future__ module
Print 9/2
Output:
4
11. Libraries:-
The advantage to use python 2 is it have a large number of libraries. Python 2 is still the
default in many operating systems like ubuntu 14.04 and 16.04 LTS. But python 3 is also
developing day by day, all the future developments will be implement in python 3 rather
than the python 2.
If you are completely beginner then recommend python 3 because it is the future of Python
and it is easy as python 2 to learn and python 3 has some additional features (eg. Function
memoiziation).
Python doesn’t convert its code into machine code, something that hardware can understand. It
actually converts it into something called byte code. So within python, compilation happens, but it’s
just not into a machine language. It is into byte code and this byte code can’t be understood by CPU.
So we need actually an interpreter called the python virtual machine. The python virtual machine
executes the byte codes.
The Python interpreter performs following tasks to execute a Python program :
Step 1: The interpreter reads a python code or instruction. Then it verifies that the instruction is well
formatted, i.e. it checks the syntax of each line. If it encounters any error, it immediately halts the
translation and shows an error message.
Step 2: If there is no error, i.e. if the python instruction or code is well formatted then the interpreter
translates it into its equivalent form in intermediate language called “Byte code”. Thus, after
successful execution of Python script or code, it is completely translated into Byte code.
Step 3: Byte code is sent to the Python Virtual Machine(PVM).Here again the byte code is executed on
PVM. If an error occurs during this execution then the execution is halted with an error message.
objects - An object is nothing but a statement that to be printed. The * sign represents that there can
be multiple statements.
sep - The sep parameter separates the print values. Default values is ' '.
end - The end is printed at last in the statement.
file - It must be an object with a write(string) method.
flush - The stream or file is forcibly flushed if it is true. By default, its value is false.
a = 10
# Two objects are passed in print() function
print("a =", a)
b=a
# Three objects are passed in print function
print('a =', a, '= b')
Output:
a = 10
print("a =", a, sep='dddd', end='\n\n\n')
print("a =", a, sep='0', end='$$$$$')
Output:
a =dddd10
a =010$$$$$
In the first print() statement, we use the sep and end arguments. The given object is printed just after
the sep values. The value of end parameter printed at the last of given object. As we can see that, the
second print() function printed the result after the three black lines.
Taking Input to the User
Python provides the input() function which is used to take input from the user.
Example:
name = input("Enter a name of student:")
print("The student name is: ", name)
Output:
Enter a name of student: Devansh
The student name is: Devansh
By default, the input() function takes the string input but what if we want to take other data types as
an input.
If we want to take input as an integer number, we need to typecast the input() function into an
integer.
Example:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a+b)
Output:
Enter first number: 50
Enter second number: 100
150
We can take any type of values using input() function.
We don't need to use data types to declare variable because it is dynamically typed so we can write
a=10 to assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no compilation step included in
Python development, and edit-test-debug cycle is very fast.
What Is Python?
Python is a general-purpose programming language. That means it was designed and developed to
write software for a wide variety of disciplines. Python has been used to write applications to solve
problems in biology, chemistry, financial analysis, numerical analysis, robotics, and many other
fields. It is also widely used as a scripting language for use by computer administrators, who use it to
capture and replay sequences of computer commands. It is different from a language like HTML
(HyperText Markup Language), which was designed for the single purpose of allowing people to specify
the layout of a web page.
Python is a widely used general-purpose, high level programming language. It was initially designed
by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly
developed for emphasis on code readability, and its syntax allows programmers to express concepts in
fewer lines of code. Python is a programming language that lets you work quickly and integrate
systems more efficiently.
There are two major Python versions- Python 2 and Python 3.
On 16 October 2000, Python 2.0 was released with many new features.
On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.