# BYTE OF PYTHON
# 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)
# 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)
#decimal precision of 3
print '{0:0.3f} and {1:0.4f}'.format(1.0/3, 2.0/3)
print '{0:*^{1}}'.format('Hello', 9)
print '{name} is employee of {company}'.format(name='Nrupatunga', company='xyz')
#print always ends with invisible new line character '\n'
a = 10
print a
# 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,
# Here \ indicates that dont print any new line character, the sentence has the continuation
"This is the first sentence. \
This is the second sentence."
'''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"
#object - Python refers to anything used in a program as object.
# Operator and expressions
# + (plus)
2 + 3
# - (minus)
2 - 3
# *(multiplication)
'la' * 3
# ** (power)
4**5
# / (division)
# observe the result here. it gives the output as integer.
13/4
# / (division)
13.0/4
#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
#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
#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!!
#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'
#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"
#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'
#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
#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'
#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()
#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)
# Local variables
x = 50
def func(x):
print 'x is', x
x = 23
print 'x is', x
func(x)
print 'x is still', x
#global variables
x = 50
def func():
global x
print 'x is', x
x = 23
print 'x is', x
func()
print 'x is now', x
#Default argument
def say(message, times=1):
print message*times
say("Hello")
say('Python', 2)
#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)
#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)
#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()
#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)
#Python modules
import sys
for i in sys.argv:
print i
print sys.path # note current directory printed as '' is also in sys.path
#The from ... import statement
from math import sqrt as sq
print 'Square root of 16 is', sq(16)
#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)
a = 5
dir() #see 'a' listed in the output
del a
dir() #now see 'a' not listed in the output
dir(str)
#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,
#Understanding iterables and iterators - Look into it only if you are interested
# http://www.shutupandship.com/2012/01/understanding-python-iterables-and.html
#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])
#Empty tuple
myempty = ()
print myempty
singleton = (1)
print type(singleton)
singleton = (1,)
print type(singleton)
#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)
#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]
#We can also provide a third argument for the slice which is the step for the
#slicing
shoplist = ['apple', 'mango', 'carrot', 'banana']
shoplist[::-2]
#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
#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
#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)
#Continued in Part-2