In [1]:
# BYTE OF PYTHON 
In [1]:
# formatting while printing
age = 28
name = 'Nrupatunga'
print '{0} was {1} when he wrote this tutorial'.format(name, age)
print 'why {0} is playing with ipython notebook'.format(name)
Nrupatunga was 28 when he wrote this tutorial
why Nrupatunga is playing with ipython notebook
In [6]:
# not needed to put the number inside {}, if you write the order of the argument correctly inside format()
print '{} was {} when he wrote this tutorial'.format(name, age)
Nrupatunga was 20 when he wrote this tutorial
In [16]:
#decimal precision of 3 
print '{0:0.3f} and {1:0.4f}'.format(1.0/3, 2.0/3)
0.333 and 0.6667
In [4]:
print '{0:*^{1}}'.format('Hello', 9)
**Hello**
In [27]:
print '{name} is employee of {company}'.format(name='Nrupatunga', company='xyz')
Nrupatunga is employee of xyz
In [28]:
#print always ends with invisible new line character '\n'
a = 10
print a
10
In [29]:
# to prevent the printing of new line character you can add comma (',') after each print statement as show below
a = 5
b = 10
print a, 
print b, 
5 10
In [30]:
# Here \ indicates that dont print any new line character, the sentence has the continuation
"This is the first sentence. \
This is the second sentence."
Out[30]:
'This is the first sentence. This is the second sentence.'
In [5]:
'''If you need to specify some strings where no special processing such as escape 
sequences are handled, then what you need is to specify a raw string by prefixing r or
R to the string.'''

r"Newlines are indicated by \n"
Out[5]:
'Newlines are indicated by \\n'
In [41]:
#object - Python refers to anything used in a program as object.
# Operator and expressions
# + (plus)
2 + 3
Out[41]:
5
In [42]:
# - (minus)
2 - 3
Out[42]:
-1
In [43]:
# *(multiplication)
'la' * 3
Out[43]:
'lalala'
In [44]:
# ** (power)
4**5
Out[44]:
1024
In [45]:
# / (division)
# observe the result here. it gives the output as integer.
13/4
Out[45]:
3
In [46]:
# / (division)
13.0/4
Out[46]:
3.25
In [7]:
#python refers anything you write in a program as object
i = 10
print i
j = i + 1
print j
s = '''This is a multiline string
this is the second line '''
print s
10
11
This is a multiline string
this is the second line 
In [1]:
#Intendation
#whitespaces are important in python, Actually, whitespace at the beginning of the line is important
#This is called intendation

#Statements which go with same indentation. Such statements are called block
i = 5
#Error below note the space in the beginning of the statement
 print 'value is ', i
print 'I repeat, the value is ', i
  File "<ipython-input-1-50b901bbb0e3>", line 8
    print 'value is ', i
    ^
IndentationError: unexpected indent
In [1]:
#I have skipped through few operators as I didn't find them so interesting, its like in every other language. So if you would like
# through them look at the book.. Hope thats ok!!
In [2]:
#Now we shall move to control flow statements
#The if statement

number = 23
#concentrate on this part, try to remember how input is taken from the user, raw_input, returns a string whatever you entered 
#on the screen
guess = int(raw_input('Enter an integer:'))

#Take a note of the colon in the after if, elif and else if you are new to python
if guess == number:
    #Note the intendation in below two statements, 
    print "Congratulations you guessed it"
    print '(But you do not win any prize!)'
#Note the elif clause here, meaning else if
elif guess < number:
    print 'No, it is a little higher than that'
else:
    print "No it is little lower than that"
    
print 'Done'

    
        
Enter an integer:24
No it is little lower than that
Done
In [4]:
#while statement
number = 23
running = True

while running:
    guess = int(raw_input("Enter an integer: "))    
    if guess == number:
        print "Congratulations you guessed it"
        running = False
    elif guess < number:
        print "No, it is little higher than that"
    else:
        print "No, it is little lower than that"
        
print "Done"
Enter an integer: 25
No, it is little lower than that
Enter an integer: 22
No, it is little higher than that
Enter an integer: 23
Congratulations you guessed it
Done
In [4]:
#for loop
#note the first and second argument are the lower and upper bound, and third argument is the step
# note the way for loop is written, "for .. in"
for i in range(1, 5, 2):
    print i
else:
    print 'The for loop is over'
1
3
The for loop is over
In [5]:
#The break statement
#Observe how else statement is use in conjunction with while statement, which is different from other languages like C, C++
while True:
    s = raw_input('Enter something: ')
    if s == 'quit':
        break
    print 'Length of the string is ', len(s)
else:
    print 'Done'
    
# An important note is that, if you break out of for or while loop, any corresponding loop 'else' block is not executed
Enter something: close
Length of the string is  5
Enter something: hello
Length of the string is  5
Enter something: quit
In [1]:
#The continue statement
#The continue statement is used to tell python to skip the rest of the statements in the current loop block and to continue to
#the next iteration of the loop
while True:
    s = raw_input('Enter something : ')
    if s == 'quit':
        break
    if len(s) < 3:
        print 'Too small, Enter something else'
        continue
    print 'Input is of sufficient length'
Enter something : Go
Too small, Enter something else
Enter something : Python is a powerful language
Input is of sufficient length
Enter something : quit
In [27]:
#Functions - How to create a function
#Functions are defined using the def keyword. After this keywork comes an identifier name for the function, followed by a pair 
#parentheses which may enclose some names of variables and by final colon ends the line. Next follows the block of statements
#that are part of this function

def say_hello():
    print 'hello, world'
    
say_hello()
say_hello()
hello, world
hello, world
In [4]:
#Function parameters
def print_max(a, b):
    if a > b:
        print a, 'is maximum'
    elif a==b:
        print a, 'is equal to', b
    else:
        print b, 'is maximum'
        

a = int(raw_input('Enter an integer a: '))
b = int(raw_input('Enter an integer b: '))
        
print_max(a, b)
print_max(3, 1)
print_max(4, 4)
print_max(1, 5)
Enter an integer a: 45
Enter an integer b: 23
45 is maximum
3 is maximum
4 is equal to 4
5 is maximum
In [8]:
# Local variables
x = 50
def func(x):
    print 'x is', x
    x = 23
    print 'x is', x
    
func(x)
print 'x is still', x
x is 50
x is 23
x is still 50
In [13]:
#global variables
x = 50

def func():
    global x
    print 'x is', x
    x = 23
    print 'x is', x
    
func()
print 'x is now', x
x is 50
x is 23
x is now 23
In [14]:
#Default argument
def say(message, times=1):
    print message*times
say("Hello")
say('Python', 2)
Hello
PythonPython
In [16]:
#passing values for only few arguments
def func(a, b=5, c=10):
    print 'a is', a, 'and b is', b, 'and c is', c

func(3,1)
func(5, c=11)
func(4, b=12)
a is 3 and b is 1 and c is 10
a is 5 and b is 5 and c is 11
a is 4 and b is 12 and c is 10
In [24]:
#variable argument
#This is interesting
#When we declare a starred parameter such as *numbers, then all the positional arguments from that point till the end are 
#collected as a tuple called 'numbers'
#when we declare a double starred parameter such as **keywords, then all the keywords arguments from that point till the end are
#collected as a dictionary called 'keywords'

def total(initial=5, *numbers, **keywords):
    count = initial
    for number in numbers:
        count = count + number
    for key in keywords:
        print key, keywords[key]
        count = count + keywords[key]
    return count

print total(10, 1, 2, eggs=3, vegetables=50, fruits=100)
eggs 3
vegetables 50
fruits 100
166
In [31]:
#return statement
def maximum(x, y):
    if x>y:
        return x
    elif x==y:
        return 'The numbers are equal'
    else:
        return y

print maximum(3, 4)

#return statement without a value is equivalent to return None, None is a special type in Python that represents nothingness. For
#example, it is used to inidicate that a variable has no value if it has a value None

#Every function implicitly has return None statement at the end unless you have written your own return statement. 
# you can see this by running print some_function() where the function some_function does not use the return

def some_function():
    pass #The pass statement is used in python to indicate an empty block of statements

print some_function()
4
None
In [34]:
#DOC STRINGS

#Python has a nifty feature called documentation strings, usually referred to by its shorted name docstrings. 
#Doc strings are important tool that you should make use of since it helps to document the program better and make it easier to 
#understand

def print_max(x, y):
    '''Prints the maximum of two numbers.'''
    if x>y:
        print x, 'is maximum'
    elif x==y:
        print x, 'is equal to', y
    else:
        print y, 'is maximum'

print_max(4, 5)
print print_max.__doc__
help(print_max)
5 is maximum
Prints the maximum of two numbers.
Help on function print_max in module __main__:

print_max(x, y)
    Prints the maximum of two numbers.

In [2]:
#Python modules
import sys
for i in sys.argv:
    print i
print sys.path # note current directory printed as '' is also in sys.path
<type 'list'>
C:\Users\nrupatunga.1\AppData\Local\Continuum\Anaconda2\lib\site-packages\ipykernel\__main__.py
-f
C:\Users\nrupatunga.1\AppData\Roaming\jupyter\runtime\kernel-1e4e2717-3a4d-4e27-8856-9556e29af25b.json
['', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2\\python27.zip', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2\\DLLs', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2\\lib', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2\\lib\\plat-win', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2\\lib\\lib-tk', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2', 'c:\\users\\nrupatunga.1\\appdata\\local\\continuum\\anaconda2\\lib\\site-packages\\sphinx-1.3.1-py2.7.egg', 'c:\\users\\nrupatunga.1\\appdata\\local\\continuum\\anaconda2\\lib\\site-packages\\setuptools-19.6.2-py2.7.egg', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2\\lib\\site-packages', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2\\lib\\site-packages\\PIL', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2\\lib\\site-packages\\cryptography-1.0.2-py2.7-win-amd64.egg', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2\\lib\\site-packages\\win32', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2\\lib\\site-packages\\win32\\lib', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2\\lib\\site-packages\\Pythonwin', 'C:\\Users\\nrupatunga.1\\AppData\\Local\\Continuum\\Anaconda2\\lib\\site-packages\\IPython\\extensions', 'C:\\Users\\nrupatunga.1\\.ipython']
In [39]:
#The from ... import statement
from math import sqrt as sq
print 'Square root of 16 is', sq(16)
Square root of 16 is 4.0
In [42]:
#The dir function
#You can use the built-in 'dir' function to list the identifier that an object defines. For example, for a module, 
# the identifiers include the functions, classes and variables defined in that module. 
import sys
dir(sys)
Out[42]:
['__displayhook__',
 '__doc__',
 '__excepthook__',
 '__name__',
 '__package__',
 '__stderr__',
 '__stdin__',
 '__stdout__',
 '_clear_type_cache',
 '_current_frames',
 '_getframe',
 '_mercurial',
 'api_version',
 'argv',
 'builtin_module_names',
 'byteorder',
 'call_tracing',
 'callstats',
 'copyright',
 'displayhook',
 'dllhandle',
 'dont_write_bytecode',
 'exc_clear',
 'exc_info',
 'exc_type',
 'excepthook',
 'exec_prefix',
 'executable',
 'exit',
 'exitfunc',
 'flags',
 'float_info',
 'float_repr_style',
 'getcheckinterval',
 'getdefaultencoding',
 'getfilesystemencoding',
 'getprofile',
 'getrecursionlimit',
 'getrefcount',
 'getsizeof',
 'gettrace',
 'getwindowsversion',
 'hexversion',
 'last_traceback',
 'last_type',
 'last_value',
 'long_info',
 'maxint',
 'maxsize',
 'maxunicode',
 'meta_path',
 'modules',
 'path',
 'path_hooks',
 'path_importer_cache',
 'platform',
 'prefix',
 'ps1',
 'ps2',
 'ps3',
 'py3kwarning',
 'setcheckinterval',
 'setprofile',
 'setrecursionlimit',
 'settrace',
 'stderr',
 'stdin',
 'stdout',
 'subversion',
 'version',
 'version_info',
 'warnoptions',
 'winver']
In [45]:
a = 5
dir() #see 'a' listed in the output
Out[45]:
['In',
 'Out',
 '_',
 '_40',
 '_41',
 '_42',
 '_43',
 '_44',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '__package__',
 '_dh',
 '_i',
 '_i1',
 '_i10',
 '_i11',
 '_i12',
 '_i13',
 '_i14',
 '_i15',
 '_i16',
 '_i17',
 '_i18',
 '_i19',
 '_i2',
 '_i20',
 '_i21',
 '_i22',
 '_i23',
 '_i24',
 '_i25',
 '_i26',
 '_i27',
 '_i28',
 '_i29',
 '_i3',
 '_i30',
 '_i31',
 '_i32',
 '_i33',
 '_i34',
 '_i35',
 '_i36',
 '_i37',
 '_i38',
 '_i39',
 '_i4',
 '_i40',
 '_i41',
 '_i42',
 '_i43',
 '_i44',
 '_i45',
 '_i5',
 '_i6',
 '_i7',
 '_i8',
 '_i9',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'a',
 'b',
 'exit',
 'func',
 'get_ipython',
 'i',
 'maximum',
 'print_max',
 'quit',
 's',
 'say',
 'say_hello',
 'some_function',
 'sq',
 'sys',
 'total',
 'x']
In [46]:
del a
dir() #now see 'a' not listed in the output
Out[46]:
['In',
 'Out',
 '_',
 '_40',
 '_41',
 '_42',
 '_43',
 '_44',
 '_45',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '__package__',
 '_dh',
 '_i',
 '_i1',
 '_i10',
 '_i11',
 '_i12',
 '_i13',
 '_i14',
 '_i15',
 '_i16',
 '_i17',
 '_i18',
 '_i19',
 '_i2',
 '_i20',
 '_i21',
 '_i22',
 '_i23',
 '_i24',
 '_i25',
 '_i26',
 '_i27',
 '_i28',
 '_i29',
 '_i3',
 '_i30',
 '_i31',
 '_i32',
 '_i33',
 '_i34',
 '_i35',
 '_i36',
 '_i37',
 '_i38',
 '_i39',
 '_i4',
 '_i40',
 '_i41',
 '_i42',
 '_i43',
 '_i44',
 '_i45',
 '_i46',
 '_i5',
 '_i6',
 '_i7',
 '_i8',
 '_i9',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'b',
 'exit',
 'func',
 'get_ipython',
 'i',
 'maximum',
 'print_max',
 'quit',
 's',
 'say',
 'say_hello',
 'some_function',
 'sq',
 'sys',
 'total',
 'x']
In [47]:
dir(str)
Out[47]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '_formatter_field_name_split',
 '_formatter_parser',
 'capitalize',
 'center',
 'count',
 'decode',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'index',
 'isalnum',
 'isalpha',
 'isdigit',
 'islower',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']
In [21]:
#Data Structures - Gets more interesting now :)

#Lists - List are enclosed in the square bracket []
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have {} items to purchase'.format(len(shoplist))
print '\nThe items I need to purchase are: '
for item in shoplist:
    print item,
    
#Appending the item rice
shoplist.append('rice')
print '\n\nThe modified list of items: '
for item in shoplist:
    print item,
    
shoplist.sort()
print '\n\n The sorted shopping list'
for item in shoplist:
    print item,
    
print '\n\nThe first item I will buy is', shoplist[0]
del shoplist[0]
for item in shoplist:
    print item,
I have 4 items to purchase

The items I need to purchase are: 
apple mango carrot banana 

The modified list of items: 
apple mango carrot banana rice 

 The sorted shopping list
apple banana carrot mango rice 

The first item I will buy is apple
banana carrot mango rice
In [22]:
#Understanding iterables and iterators - Look into it only if you are interested
# http://www.shutupandship.com/2012/01/understanding-python-iterables-and.html
In [30]:
#Tuple

#Tuples are used to hold together multiple objects. Think of them similar to list
#but without the extensive functionality that the list class gives. One major 
#feature of tuples is that they are immutable like strings i.e., you cannot 
#modify tuples

zoo = ('python', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)

new_zoo = 'monkey', 'camel', zoo
print 'Number of animals in the zoo is', len(new_zoo)

print 'All the animals in the new zoo are', new_zoo
print 'All the animals brought from old zoo are', new_zoo[2]
print 'Last animal brought from the old zoo are', new_zoo[2][2]

print 'Number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2])
Number of animals in the zoo is 3
Number of animals in the zoo is 3
All the animals in the new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
All the animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from the old zoo are penguin
Number of animals in the new zoo is 5
In [37]:
#Empty tuple
myempty = ()
print myempty

singleton = (1)
print type(singleton)

singleton = (1,)
print type(singleton)
()
<type 'int'>
<type 'tuple'>
In [49]:
#Dictionary

#A dictionary is like a address book, you can find the address or contact 
#details of a person by knowing only his/her name i.e., we associate keys with
#values. 

#Note that key must be unique just like we cannot find out the correct 
#information if you have two persons with exact same name

ab = {'nrupatunga': 'nrupatunga@gmail.com', 
        'Larry': 'larry@wall.org', 
        'Matsumoto': 'matz@ruby-lang.com', 
         'Spammer': 'spammer@hotmail.com'}
print type(ab)

print "Nrupatunga's address is", ab['nrupatunga']
for name, address in ab.iteritems():#itemitems are the efficient implementation of method items()
    print 'contact {} at {}'.format(name, address)
    
del ab['Spammer']

print '\n\n'

for name, address in ab.iteritems():
    print 'contact {} at {}'.format(name, address)

    
<type 'dict'>
Nrupatunga's address is nrupatunga@gmail.com
contact Matsumoto at matz@ruby-lang.com
contact Larry at larry@wall.org
contact Spammer at spammer@hotmail.com
contact nrupatunga at nrupatunga@gmail.com



contact Matsumoto at matz@ruby-lang.com
contact Larry at larry@wall.org
contact nrupatunga at nrupatunga@gmail.com
In [1]:
#Sequence
#Lists, tuples and strings are examples of sequences, but what are sequences
# and what's special about them

#The major features are membership tests, i.e., the 'in' and 'not in' 
# expressions and the indexing operations, which allows us to retrieve a slice 
# of sequence i.e., a part of the sequence

shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'nrupatunga'

print 'item 0 is', shoplist[0]
print 'item -1 is', shoplist[-1] 
print 'item -2 is', shoplist[-2]

print 'item start to end', shoplist[0:-1]
print 'item start to end', shoplist[:]

print name[0:]
print name[0:5]
item 0 is apple
item -1 is banana
item -2 is carrot
item start to end ['apple', 'mango', 'carrot']
item start to end ['apple', 'mango', 'carrot', 'banana']
nrupatunga
nrupa
In [73]:
#We can also provide a third argument for the slice which is the step for the 
#slicing 

shoplist = ['apple', 'mango', 'carrot', 'banana']
shoplist[::-2]
Out[73]:
['banana', 'mango']
In [80]:
#Set

#Sets are unordered collections of simple objects. These are used when the 
#existence of an object in a collection is more important than the order or how 
#many times it occurs

bri = set(['brazil', 'russia', 'india'])

print 'india' in bri
print 'usa' in bri
bric = bri.copy()
bric.add('china')
print bric.issuperset(bri)
bri.remove('russia')
bri & bric
True
False
True
Out[80]:
{'brazil', 'india'}
In [85]:
#References

print 'Simple assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist #points to the same object

del shoplist[0]
print shoplist
print mylist

mylist = shoplist[:] #slicing create a new object type mylist of type list

del shoplist[0]
print shoplist
print mylist
Simple assignment
['mango', 'carrot', 'banana']
['mango', 'carrot', 'banana']
['carrot', 'banana']
['mango', 'carrot', 'banana']
In [99]:
#More about strings

#Strings are also objects and have methods which do everything from checking 
#part of a string to stripping string

#The strings which we use in the program are all objects of the class 'str'

name = 'Nrupatunga'
if name.startswith('Nrup'):
    print 'yes it starts with "Nrup"'

if 'a' in name:
    print 'yes, it contains the string "a"'

if name.find('tunga') != -1:
    print 'Yes it contains the word "tunga"'
    
mylist = ['Andrew', 'YaanLecun', 'Yoshua']
delimiter = ' ' #Note how this works, it nice know!
print delimiter.join(mylist)
yes it starts with "Nrup"
yes, it contains the string "a"
Yes it contains the word "tunga"
Andrew YaanLecun Yoshua
In [ ]:
#Continued in Part-2