Python Training at VMWare Bangalore - Day

Sep 18-20 2017 Vikrant Patil

These notes are available online at http://notes.pipal.in/2017/vmware-python

© Pipal Academy LLP

Day 1 | Day 2 | Day 3

Quick start to python

In [1]:
1
Out[1]:
1
In [2]:
1.2
Out[2]:
1.2
In [3]:
x = 3
In [4]:
x
Out[4]:
3
In [5]:
print(x)
3
In [6]:
name = "krishna"
In [7]:
print(name)
krishna
In [8]:
raga = input()
asawary
In [9]:
print(raga)
asawary

Integers

In [11]:
2 + 2
Out[11]:
4
In [12]:
2 - 3
Out[12]:
-1
In [13]:
2 * 3
Out[13]:
6
In [14]:
2 ** 3
Out[14]:
8
In [15]:
9 % 2
Out[15]:
1
In [16]:
2 ** 100
Out[16]:
1267650600228229401496703205376
In [17]:
2 ** 1000
Out[17]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
In [18]:
5 // 2
Out[18]:
2
In [19]:
5 / 2
Out[19]:
2.5

Floting point numbers

In [20]:
0.0001 + 1
Out[20]:
1.0001

Strings

In [22]:
first = "Rupali"
second = "Rupak"
In [23]:
print(first, second)
Rupali Rupak
In [24]:
"Rupali" "Rupak"
Out[24]:
'RupaliRupak'
In [25]:
name = "Rupali" "Rupak"
In [26]:
name
Out[26]:
'RupaliRupak'
In [27]:
first + second
Out[27]:
'RupaliRupak'
In [28]:
name = first + " " + second
In [29]:
name
Out[29]:
'Rupali Rupak'
In [30]:
five = str(5)
In [31]:
five
Out[31]:
'5'
In [32]:
star = "*"
In [34]:
fivestar = star * 5
In [35]:
fivestar
Out[35]:
'*****'
In [37]:
print("*"*50)
**************************************************

It also supports usual escape chars

In [38]:
twolines = "first line \n second line"
In [39]:
print(twolines)
first line 
 second line
In [40]:
columns = "column1\tcolumn2"
In [41]:
print(columns)
column1	column2
In [42]:
multiline = """
pthon is very simple
python is very powerfull
python is very close to human language , english
and it has nothing do with snakes, but it is related 
BBC's monty python show
"""
In [43]:
multiline
Out[43]:
"\npthon is very simple\npython is very powerfull\npython is very close to human language , english\nand it has nothing do with snakes, but it is related \nBBC's monty python show\n"
In [44]:
print(multiline)
pthon is very simple
python is very powerfull
python is very close to human language , english
and it has nothing do with snakes, but it is related 
BBC's monty python show

In [45]:
print("\u0c85")
ಅ
In [47]:
print("I can have ' single quote inside")
I can have ' single quote inside
In [48]:
print('I can have " double quote inside')
I can have " double quote inside
In [50]:
'something'
Out[50]:
'something'

It has binary data

In [52]:
binary = b'binary'
In [53]:
print(binary)
b'binary'
In [54]:
hex(5)
Out[54]:
'0x5'
In [55]:
hex(ord("b"))
Out[55]:
'0x62'
In [56]:
binary = b'\x62\x69\x6e'
In [58]:
print(binary)
b'bin'

High level data type called lists

In [59]:
letters = ['a','b','c']
In [60]:
letters
Out[60]:
['a', 'b', 'c']
In [61]:
letters[0]
Out[61]:
'a'
In [62]:
letters[1]
Out[62]:
'b'
In [63]:
len(letters)
Out[63]:
3
In [64]:
ones = [1,1,1,1]
In [65]:
moreones = ones + ones
In [66]:
moreones
Out[66]:
[1, 1, 1, 1, 1, 1, 1, 1]
In [67]:
multidata = ["a", 1, "Three", ones]
In [68]:
multidata
Out[68]:
['a', 1, 'Three', [1, 1, 1, 1]]
In [69]:
multidata[0]
Out[69]:
'a'
In [70]:
multidata[2]
Out[70]:
'Three'
In [71]:
multidata[3]
Out[71]:
[1, 1, 1, 1]
In [72]:
multidata[0] = "b"
In [73]:
multidata
Out[73]:
['b', 1, 'Three', [1, 1, 1, 1]]
In [74]:
topten = list(range(10))
In [75]:
topten
Out[75]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [76]:
topten[-1]
Out[76]:
9
In [77]:
topten[-2]
Out[77]:
8
In [78]:
topten[:2]
Out[78]:
[0, 1]
In [79]:
topten[2:]
Out[79]:
[2, 3, 4, 5, 6, 7, 8, 9]
In [80]:
topten[5:7]
Out[80]:
[5, 6]
In [81]:
someotherlist = ['a', 'b','c','d','e']
In [82]:
someotherlist[0]
Out[82]:
'a'
In [83]:
someotherlist[2:4]
Out[83]:
['c', 'd']
In [84]:
someotherlist[1:4:2]
Out[84]:
['b', 'd']
In [85]:
someotherlist[1:4:-1]
Out[85]:
[]
In [88]:
someotherlist[4:0:-1]
Out[88]:
['e', 'd', 'c', 'b']
In [87]:
len(someotherlist)
Out[87]:
5
In [89]:
someotherlist[1:4][-1]
Out[89]:
'd'
In [90]:
someotherlist[::-1]
Out[90]:
['e', 'd', 'c', 'b', 'a']

matrix

In [91]:
matrix = [[1,2,3], [2,3,4],[5,6,7]]
In [92]:
matrix
Out[92]:
[[1, 2, 3], [2, 3, 4], [5, 6, 7]]
In [93]:
matrix[0] 
Out[93]:
[1, 2, 3]
In [94]:
matrix[-1]
Out[94]:
[5, 6, 7]
In [95]:
matrix[0][-1]
Out[95]:
3

There is a sibling of list caleed tuple. tuple is just like list, but immutable.

In [96]:
point = (1.1, 2.0)
In [97]:
point[0]
Out[97]:
1.1
In [98]:
point[1]
Out[98]:
2.0
In [99]:
traingle = ((0,0),(0,1),(1,1))
In [100]:
traingle[0]
Out[100]:
(0, 0)
In [101]:
traingle[0] = (0,3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-101-4a7f9c0e226e> in <module>()
----> 1 traingle[0] = (0,3)

TypeError: 'tuple' object does not support item assignment
In [102]:
ones = (1,1,1)
In [103]:
ones + ones
Out[103]:
(1, 1, 1, 1, 1, 1)
In [104]:
ones
Out[104]:
(1, 1, 1)
In [105]:
ones + ones
Out[105]:
(1, 1, 1, 1, 1, 1)
In [106]:
mutable = list(ones)
In [107]:
mutable
Out[107]:
[1, 1, 1]
In [108]:
mutable[0] = 0
In [109]:
mutable
Out[109]:
[0, 1, 1]
In [110]:
ones
Out[110]:
(1, 1, 1)

Dictionaries are named collection of objects. You retrive objects aby names instead of index

In [111]:
machine = {"name":"mozart", "os":"ubuntu", "make":"acer"}
In [112]:
machine
Out[112]:
{'make': 'acer', 'name': 'mozart', 'os': 'ubuntu'}
In [113]:
machine['name']
Out[113]:
'mozart'
In [114]:
machine['os']
Out[114]:
'ubuntu'
In [115]:
machine["key"] = 5
In [116]:
machine
Out[116]:
{'key': 5, 'make': 'acer', 'name': 'mozart', 'os': 'ubuntu'}
In [117]:
machine
Out[117]:
{'key': 5, 'make': 'acer', 'name': 'mozart', 'os': 'ubuntu'}

set :Python has datatype set which allows us to store data as a set.

In [119]:
paragraph = """
I have random fiction
written for this trp aining
and we want to find how many english charecters are used in it
"""
In [120]:
set(paragraph)
Out[120]:
{'\n',
 ' ',
 'I',
 'a',
 'c',
 'd',
 'e',
 'f',
 'g',
 'h',
 'i',
 'l',
 'm',
 'n',
 'o',
 'p',
 'r',
 's',
 't',
 'u',
 'v',
 'w',
 'y'}
In [121]:
set([2,2,3,4,5,6,7,8,11,11,12,13])
Out[121]:
{2, 3, 4, 5, 6, 7, 8, 11, 12, 13}

and offcourse boolean

In [122]:
sure = True
arrr = False
In [124]:
print(sure, arrr)
True False

There is one very special object for nothing!

In [127]:
nothing = None
In [128]:
print(nothing)
None
In [129]:
nothing
In [130]:
a = {1,2}
In [131]:
a
Out[131]:
{1, 2}
In [132]:
a = {[1,2,3], [1,2,3]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-132-5cdb72b857a9> in <module>()
----> 1 a = {[1,2,3], [1,2,3]}

TypeError: unhashable type: 'list'

Do it yourself

  • will this work?
    pre = "Isac"
    post = "Asimov"
    name = pre post
  • What will be output of following sequence of command in interpreter, observe the special variable _
    2 ** 2
    _
    a = 5 * 6
    _
    _ = 67
    a/6 
    _
    31 // 6

Functions

Lets see some built in functions
In [133]:
len("Python")
Out[133]:
6
In [134]:
len((1,2,3,4))
Out[134]:
4
In [135]:
len([1,2,3,4,5,6,7])
Out[135]:
7
In [136]:
len({"a":1})
Out[136]:
1
In [137]:
len(set("Hello"))
Out[137]:
4
In [138]:
4 + "2"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-138-2957f6c14a52> in <module>()
----> 1 4 + "2"

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [139]:
str(4) + "2"
Out[139]:
'42'

Problem : Using known functions find out number of digits in 2**100

In [140]:
len(str(2**100))
Out[140]:
31
In [141]:
digits = str(2**100)
In [142]:
digits
Out[142]:
'1267650600228229401496703205376'
In [143]:
len(digits)
Out[143]:
31

Custom functions

In [145]:
def square(x):
    return x*x

def say_hello(name):
    print("Hello", name)
In [146]:
square(5)
Out[146]:
25
In [147]:
say_hello("hari")
Hello hari
In [148]:
s = square(5)
In [149]:
s
Out[149]:
25
In [150]:
r = say_hello("hari")
Hello hari
In [151]:
r
In [152]:
print(r)
None
In [153]:
say_hello(5)
Hello 5
In [154]:
print("Hello{}".format("hari"))
Hellohari

Do it youself

  • Write function count_digits to count number of digits in a given number.
    count_digits(100)
    3
In [155]:
def twice(x):
    return 2*x

def twice1(x):
    print(2*x)
In [156]:
twice(twice(3))
Out[156]:
12
In [157]:
twice1(twice1(3))
6
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-157-c3f6229d2002> in <module>()
----> 1 twice1(twice1(3))

<ipython-input-155-3d4ed9845aa2> in twice1(x)
      3 
      4 def twice1(x):
----> 5     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

More about functions

Functions in python are nothing special as compared to other data types. but makes it very special

In [158]:
def func(x):
    return x*x
In [159]:
print(func)
<function func at 0x7f8f0c1b0488>
In [160]:
print([1,2,3])
[1, 2, 3]
In [161]:
type([1,2,3])
Out[161]:
list
In [162]:
type(1)
Out[162]:
int
In [163]:
type(func)
Out[163]:
function
In [164]:
f = func
In [165]:
func(2)
Out[165]:
4
In [166]:
f(2)
Out[166]:
4
In [168]:
print(f)
<function func at 0x7f8f0c1b0488>
In [169]:
print(func)
<function func at 0x7f8f0c1b0488>
In [174]:
def summation(x,y):
    return x+y

def square(x):
    return x*x

def sumaofsquares(x, y):
    return square(x) + square(y)
In [175]:
def cube (x):
    return x**3

def sumofcubes(x,y):
    return cube(x) + cube(y)
In [176]:
def sumof(x, y, f):
    return f(x) + f(y)
In [177]:
sumaofsquares(2,3)
Out[177]:
13
In [178]:
sumof(2, 3, square)
Out[178]:
13
In [179]:
def cube (x):
    return x**3

def square(x):
    return x*x

def sumof(x, y, f):
    return f(x) + f(y)
In [180]:
sumof(2,3, cube)
Out[180]:
35
In [181]:
sq = lambda x: x*x
In [182]:
sumof(2,3, sq)
Out[182]:
13
In [183]:
def make_adder(y):
    return lambda x: x+y
In [184]:
add2 = make_adder(2)
In [185]:
print(add2)
<function make_adder.<locals>.<lambda> at 0x7f8f0c1b06a8>
In [186]:
add2(10)
Out[186]:
12

There are some built in functions which take functions as argument

In [187]:
max(4,5)
Out[187]:
5
In [188]:
max([1,2,3,4,5])
Out[188]:
5
In [189]:
max(["one", "two", "three", "four", "five"])
Out[189]:
'two'
In [190]:
words = ["one", "two", "three", "four", "five"]
In [191]:
max(words, key=len)
Out[191]:
'three'
In [192]:
min(words, key=len)
Out[192]:
'one'

We have record which contains scores of students stores as tuple in a list. We wish to find a student with max score.

In [196]:
scroresheet = [("vinay", 8.8, 14),
              ("vijay", 9.0, 14),
              ("vijaya", 9.9, 13),
              ("vishakha", 9.1, 12)]
In [197]:
def get_score(record):
    return record[1]
In [198]:
max(scroresheet, key=get_score)
Out[198]:
('vijaya', 9.9, 13)
In [199]:
max(scroresheet)
Out[199]:
('vishakha', 9.1, 12)
In [200]:
max(scroresheet, key= lambda r:r[1])
Out[200]:
('vijaya', 9.9, 13)

Methods from objects

Objects of built in data type has some usefull functions as part of object. Those are called methods

string

In [201]:
book = "Alice in wonderland"
In [202]:
book.lower()
Out[202]:
'alice in wonderland'
In [203]:
book.upper()
Out[203]:
'ALICE IN WONDERLAND'
In [204]:
book.count('n')
Out[204]:
3
In [206]:
book.split(" ")
Out[206]:
['Alice', 'in', 'wonderland']
In [207]:
book.replace(" ","_")
Out[207]:
'Alice_in_wonderland'
In [208]:
book.startswith("Alice")
Out[208]:
True
In [209]:
book.endswith("alice")
Out[209]:
False

lists

In [210]:
numbers = list(range(5,25,2))
In [211]:
numbers
Out[211]:
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
In [212]:
numbers.count(5)
Out[212]:
1
In [213]:
numbers.count(" ")
Out[213]:
0
In [214]:
numbers.reverse()
In [215]:
numbers
Out[215]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5]
In [216]:
numbers.append(0)
In [217]:
numbers
Out[217]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 0]
In [218]:
numbers.pop()
Out[218]:
0
In [219]:
numbers
Out[219]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5]
In [220]:
numbers.sort(reverse=True)
In [221]:
numbers
Out[221]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5]
In [222]:
names = ['asawary', 'bahiravi','kalashri','tilak kamod']
In [223]:
names.sort()
In [224]:
names
Out[224]:
['asawary', 'bahiravi', 'kalashri', 'tilak kamod']
In [227]:
names.sort(reverse=True,key=len)
In [228]:
names
Out[228]:
['tilak kamod', 'bahiravi', 'kalashri', 'asawary']
In [229]:
names.extend(['yaman', 'malkauns'])
In [230]:
names
Out[230]:
['tilak kamod', 'bahiravi', 'kalashri', 'asawary', 'yaman', 'malkauns']

tuple

In [231]:
numbers = (1,2,3,4)
In [233]:
numbers.count(1)
Out[233]:
1
In [234]:
numbers.index(3)
Out[234]:
2

DO it yourself

  • Write a function to count zeros in a given number

    count_zeros(100)
    2
  • Write a function head that takes list of words and returns first n words by dictionary order

    head(['python','lisp', 'haskell', 'ocamel','ark', 'java'], 3)
    ['ark', 'haskell', 'java']
In [236]:
def count_zeros(n):
    return str(n).count('0')

def head(words, n):
    words.sort()
    return words[:n]
In [237]:
count_zeros(2**100)
Out[237]:
6
In [238]:
head(['python','lisp', 'haskell', 'ocamel','ark', 'java'], 3)
Out[238]:
['ark', 'haskell', 'java']

modules

For convinience related functions are organised inside a module. you can import these modules make use of functions or objects from that module

In [239]:
import math

def area_circle(radius):
    return math.pi * radius * radius

def polar_to_ractangular(radius, theta):
    return radius*math.cos(theta), radius*math.sin(theta)
In [241]:
area_circle(1)
Out[241]:
3.141592653589793
In [242]:
polar_to_ractangular(1, math.pi/2)
Out[242]:
(6.123233995736766e-17, 1.0)
In [243]:
x,y = polar_to_ractangular(1, 0)
In [244]:
x, y
Out[244]:
(1.0, 0.0)
In [245]:
x, y = y , x
In [246]:
x, y
Out[246]:
(0.0, 1.0)
In [247]:
import os
In [248]:
os.getcwd()
Out[248]:
'/home/vikrant/trainings/2017/vmware-python'
In [250]:
os.getenv("PATH")
Out[250]:
'/home/vikrant/usr/local/jupyter/bin:/home/vikrant/usr/local/jupyter/bin:/home/vikrant/bin:/home/vikrant/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games'
In [252]:
os.getlogin()
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-252-64defab13146> in <module>()
----> 1 os.getlogin()

OSError: [Errno 25] Inappropriate ioctl for device
In [253]:
os.mkdir("/tmp/test1")
In [254]:
!ls /tmp/
config-err-0wn9Kp
firefox_vikrant
libgksu-2MwCiY
mintUpdate
ssh-J7HMapUgnss6
systemd-private-7e44d48da2304c6da1a992411d9711c9-colord.service-jaYyWy
systemd-private-7e44d48da2304c6da1a992411d9711c9-rtkit-daemon.service-E69o88
test1
In [255]:
os.listdir("/tmp/")
Out[255]:
['libgksu-2MwCiY',
 '.XIM-unix',
 'ssh-J7HMapUgnss6',
 '.font-unix',
 'systemd-private-7e44d48da2304c6da1a992411d9711c9-rtkit-daemon.service-E69o88',
 'systemd-private-7e44d48da2304c6da1a992411d9711c9-colord.service-jaYyWy',
 'firefox_vikrant',
 '.ICE-unix',
 'config-err-0wn9Kp',
 '.X11-unix',
 'test1',
 '.X0-lock',
 '.Test-unix',
 'mintUpdate']
In [257]:
os.path.exists("/tmp/test1")
Out[257]:
True
In [259]:
os.path.getsize("./Makefile")
Out[259]:
617

Do it yourself

  • write a function countfiles to count number of files in a given directory
  • write a function biggestfile to find biggest file in a given directory
In [262]:
def biggestfile(directory):
    files = os.listdir(directory)
    return max(files, key=os.path.getsize)
In [261]:
biggestfile(os.getcwd())
Out[261]:
'day1.html'

Custom modules

custom modules can be written by writing python statements and functions inside file with extension .py

In [263]:
%%file mymodule.py
import sys

def say_hello(name):
    print("Hello ", name)
    
print(sys.argv)
Writing mymodule.py
In [264]:
!python mymodule.py 
['mymodule.py']
In [265]:
!python mymodule.py hello 1 2 3
['mymodule.py', 'hello', '1', '2', '3']
In [266]:
import mymodule
['/home/vikrant/usr/local/jupyter/lib/python3.5/site-packages/ipykernel_launcher.py', '-f', '/run/user/1000/jupyter/kernel-945e24ab-abf4-444f-a309-3861c167a644.json']
In [267]:
mymodule.say_hello("Python")
Hello  Python
In [268]:
help(mymodule)
Help on module mymodule:

NAME
    mymodule

FUNCTIONS
    say_hello(name)

FILE
    /home/vikrant/trainings/2017/vmware-python/mymodule.py


In [269]:
import random
In [270]:
random.choice(["python","lisp","haskell", "java"])
Out[270]:
'python'
In [271]:
random.choice(["python","lisp","haskell", "java"])
Out[271]:
'haskell'
In [274]:
senestence = "Pascal traingle is very simple structure but it has got very interesting properties"
In [275]:
random.choice(senestence.split())
Out[275]:
'has'

Do it yourself

  • write a python script square.py that takes a number as commandline argument and prints square of that number
  • write a python script add.py that takes a two numbers as commandline arguments and prints addition of those numbers
  • write a python script echo.py which echoes whatever argument is given
In [276]:
%%file square.py
import sys

def square(x):
    return x*x

x = int(sys.argv[1])
value = square(x)
print(value)
Writing square.py
In [277]:
!python square.py 3
9
In [278]:
%%file echo.py
import sys

print(sys.argv[1:])
Writing echo.py
In [279]:
!python echo.py echoes this statement till end
['echoes', 'this', 'statement', 'till', 'end']
In [281]:
"_".join(["hello", "world", "make", "statement"])
Out[281]:
'hello_world_make_statement'
In [284]:
%%file echo.py
import sys

print(" ".join(sys.argv[1:]))
Overwriting echo.py
In [285]:
!python echo.py echoes this statement till end
echoes this statement till end

there is special variable __name__

In [286]:
%%file anothermodule.py
print(__name__)
Writing anothermodule.py
In [287]:
!python anothermodule.py
__main__
In [288]:
import anothermodule
anothermodule
In [303]:
%%file echo.py
import sys

def echo():
    x = 0
    print(" ".join(sys.argv[1:]))
    
print(__name__)

if __name__ == "__main__":
    echo()
Overwriting echo.py
In [304]:
import echo
In [302]:
!python echo.py some commandline arguments
__main__
some commandline arguments