Skip to main content

Difference between Python 2 and 3

Here you will know about difference between python 2 and 3.

As a newbie, everyone confuses that which version of Python should learn and use (Python 2.x or 3.x, where x means versions). Let’s see the key differences between them.

Python 2 vs 3 - Difference between Python 2 and 3

Image Source

Python 2 vs 3 – Difference between Python 2 and 3

  Python 2 Python 3
1. Integer Division print 9/2

>> 4

print(9/2)

>> 4.5

2. Print function print “Hello world”

>>Hello world

print(“Hello world”)

>>Hello world

3. Unicode print type(Unicode(“Hello”))

>>  <type ‘unicode’>

 

print type(b’Hello’)

>> <type ‘str’>

 

print ‘hello’ +  b’ world’

>>hello world

 

print type(bytearray(b’hello world’))

>> <type ‘bytearray’> 

print (‘\u03BCnico\u394e!’)

>> µnico∆e!

 

print(type(b’hello’))

>> <class ‘bytes’>

 

print(‘hello’ + b’ world’))

>> TypeError

 

print(type(bytearray(b’hello’)))

>> <class ‘bytearray’>

4. xrange function Support range() and xrange() both. have no xrange() function but range() function will behave like xrange() in python 2.
5. Raising exception raise IOError, “file not found”

>>IOError: file not found

raise IOError(“file not found”)

>>IOError: file not found                           

6. Handling exception try:

  print 4/0

except ZeroDivisionError, err:

  print “can’t divide by zero”

  print “error – “ + err

output:

can’t divide by zero

error – integer division or modulo by zero

try:

  print(4/0)

except ZeroDivisionError as err:

  print(“can’t divide by zero”)

  print(“error –“ + str(err))

output:

can’t divide by zero

error – division by zero

7. Leak of for-loop variables in global namespace i = 1

print ‘before: i = ‘, i

print ‘loop:’,[i for i in range(5)]

print ‘after:i = ‘, i

Output:

before: i =1

loop: [0,1,2,3,4]

after: i = 4

i = 1

print(‘before :i =’, i)

print(‘loop:’ [i for i in range(5)])

print(‘after: i = ‘, i)

Output:

before: i = 1

loop: [0,1,2,3,4]

after: i = 1

8. .next() method have next() function and .next() method for iterate next element.

list1 = [4, 43, 34,  32]

iterator = iter(list1)

print iterator.next()

print next(iterator)

print iterator.next()

Output:

4

43

34

Have only next() function.

list1 = [4, 43, 34, 32]

iterator = iter(list1)

print (next(iterator))

print (next(iterator))

print (next(iterator))

Output:

4

43

34

9. input() method We can use both raw_input() and input() method.

s = raw_input(“enter something:”)

raw_input() is replaced by input() method. There is no raw_input() method.

s = input(“enter something:”)

Let’s understand these differences in detail.

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.

So if you’re completely beginner then we 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).

Comment below if you have queries related to above tutorial for difference between python 2 and 3.

The post Difference between Python 2 and 3 appeared first on The Crazy Programmer.



from The Crazy Programmer https://www.thecrazyprogrammer.com/2018/01/difference-python-2-3.html

Comments

Popular posts from this blog

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan...

15 Web Design Trends to Watch in 2018

The modern world is full of extraordinary things that influence our imagination and mood. Our soul needs a perfect atmosphere and impressive spots. To apply such things in practice, we have submitted the list of the web trends that deserve your attention. Robert frost design analysis will meet all your wishes and expectations. Image Source Web Design Trends to Watch in 2018 1. More Organic Shapes Until this year, web design, as well as mobile design, were based on the right-angled and sharp-edged shapes. However, it seems that this year will bring some significant changes in the field of web design. The recent trends will offer the absolute rounded corners. In addition, the web design of 2018 will make the real things look like the cartoonish ones. 2.   Bold Minimalism Although some of you may think that this web design trend will not attract the Internet users. Indeed, the notion of minimalism is often associated with boredom and dullness. However, in this case, bold ...

R vs Python for Machine Learning

There are so many things to learn before to choose which language is good for Machine Learning. We will discuss each and everything about R as well as Python and the situation or problem in which situation we have to use which language. Let’s start Python and R are the two most Commonly used Programming Languages for Machine Learning and because of the popularity of both the languages Novice or you can say fresher are getting confused, whether they should choose R or Python language to commence their career in the Machine learning domain. Don’t worry guys through this article we will discuss R vs Python for Machine Learning. So, without exaggerating this article let’s get started. We will start it from the very Basics things or definitions. R vs Python for Machine Learning Introduction R is a programming language made by statisticians and data miners for statistical analysis and graphics supported by R foundation for statistical computing. R also provides high-quality graphics and...