Introduction to Python

Python 2 -> Python 3

 

 

Python 3:  introduced Dec. 2008; in active development

Python 2:  introduced Oct. 2000, developed until mid-2010; legacy

 

Python 3 is not backward-compatible with Python 2.  However at a basic level, differences are minimal.  This list is not exhaustive, but covers the basics. 

 


Python 3

Python 2



print() is a function

 

print('hello!')
print('hello!', end='')

print('hello', 'world!')

print('hello', 'world!', sep='')

 


print is a statement

 

print 'hello!'

sys.stdout.write('hello!')

print 'hello', 'world!'

 


 

 


integer division results in float

 

print(5/3)   # 1.6666666666666667

print(4/2)   # 2.0


Integer division results in int

 

print 5/3        # 1

print 5/3.0      # 1.6666666666667



 

 

 


input(): take interactive keyboard input

 

num = input('pls enter a num: ')


raw_input():  same

 

num = raw_input('pls enter a num: ')


 

Note that input() in Python 2 runs an "eval" (code evaluation and execution) on user input. 

 

 

Selected functions and methods return iterators or views instead of lists.  These can be used in for looping and in functions that accept iterables.  To produce lists in Python 3, these can be passed to list(). 

 


range():  return an iterator of integers

zip():  return an iterator of 2-item tuples

map():  return an iterator of items

dict.keys():  return a view of dict keys

dict.values():  return a view of dict values

dict.items():  return a view of dict items

range():  return a list of integers

zip():  return a list of 2-item tuples

map():  return a list of items

dict.keys():  return a list of dict keys

dict.values():  return a list of dict values

dict.items():  return a list of dict items


 

 


All strings are Unicode by default

All strings are ascii by default