Basic Python Training at PCCOE - Day 2

March 5-7, 2019 Vikrant Patil

These notes are available online at http://notes.pipal.in/2019/pccoe_basic/day2.html

© Pipal Academy LLP

Day 1 | Day 2 | Day 3

We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from

https://www.anaconda.com/download/

conditions

In [1]:
yes = True
In [2]:
filename = "hello.py"
In [3]:
filename.endswith(".py")
Out[3]:
True
In [4]:
if filename.endswith(".py"):
    print("Python file")
else:
    print("other")
Python file
In [5]:
def filetype(filename):
    if filename.endswith(".py"):
        return "python"
    else:
        return "Unknown"
In [6]:
filetype("square.py")
Out[6]:
'python'
In [7]:
filetype("windows.exe")
Out[7]:
'Unknown'
In [8]:
def filetype_(filename):
    if filename.endswith(".py"):
        return "python"
    elif filename.endswith(".exe"):
        return "executable"
    elif filename.endswith(".hs"):
        return "haskell"
    elif filename.endswith(".doc"):
        return "word"
    elif filename.endswith(".xls"):
        return "excel"
    else:
        return "Unknown"
In [9]:
filetype_("test.xls")
Out[9]:
'excel'
In [10]:
languages = ["python", "c", "c++", "lisp", "javascript"]
In [11]:
"python" in languages
Out[11]:
True
In [13]:
"english" in languages
Out[13]:
False
In [14]:
person = {"name":"Alice","age":13,"country":"wonderland"}
In [15]:
"name" in person
Out[15]:
True
In [16]:
"language" in person
Out[16]:
False
In [17]:
"country" in person
Out[17]:
True
In [18]:
s = "Answer to every question of life is 42"
In [19]:
"Answer" in s
Out[19]:
True
In [20]:
"42" in s
Out[20]:
True
In [21]:
"Question" in s
Out[21]:
False
In [22]:
"42" in s and "haskell" in languages
Out[22]:
False
In [23]:
"english" in languages or "life" in s 
Out[23]:
True
In [24]:
2 == 2
Out[24]:
True
In [25]:
2 ==3 
Out[25]:
False
In [26]:
2 <= 3
Out[26]:
True
In [27]:
2 < 3
Out[27]:
True
In [28]:
2 != 3
Out[28]:
True
In [29]:
def even(n):
    return n%2==0
In [30]:
even(4)
Out[30]:
True
In [31]:
even(7)
Out[31]:
False
In [32]:
def odd(n):
    return not even(n)

problem

  • Write a function minimum2 which finds minimum of given two numbers x,y.

  • Write a function minimum3 which finds minimum of given three number x, y, z

In [33]:
def minimum2(x,y):
    if x < y:
        return x
    else:
        return y
In [34]:
def minimum3(x,y,z):
    t = minimum2(x,y)
    return minimum2(t, z)

modules

In [35]:
%%file square.py
import sys

def square(x):
    return x*x


x = float(sys.argv[1])
print(square(x))
Writing square.py
In [37]:
!python square.py 5.6
31.359999999999996
In [38]:
import square
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-38-9e928442ab9c> in <module>
----> 1 import square

~/trainings/2019/pccoe_basic/square.py in <module>
      5 
      6 
----> 7 x = float(sys.argv[1])
      8 print(square(x))

ValueError: could not convert string to float: '-f'
In [39]:
%%file square1.py
import sys

def square(x):
    return x*x

if __name__=="__main__":
    x = float(sys.argv[1])
    print(square(x))
Writing square1.py
In [40]:
!python square1.py 4.4
19.360000000000003
In [41]:
import square1
In [42]:
square1.square(4.5)
Out[42]:
20.25
In [43]:
%%file square2.py
import sys

def square(x):
    return x*x

print(__name__)

if __name__=="__main__":
    x = float(sys.argv[1])
    print(square(x))
Writing square2.py
In [44]:
!python square2.py 5.6
__main__
31.359999999999996
In [45]:
import square2
square2

while loop

In [46]:
import time
x = 10
while x > 0:
    print("T-", x)
    x = x -1 # x -= 1
    time.sleep(1)
T- 10
T- 9
T- 8
T- 7
T- 6
T- 5
T- 4
T- 3
T- 2
T- 1
In [47]:
x, y = 2, 3
In [48]:
x
Out[48]:
2
In [49]:
y
Out[49]:
3
In [54]:
def print_fibonacci(n):
    curr , prev = 1, 0
    while curr <= n:
        print(curr, end=",")
        curr, prev = prev+curr, curr
        
        
In [55]:
print_fibonacci(100)
1,1,2,3,5,8,13,21,34,55,89,

for loop

In [56]:
fibs = [1,1,2,3,5,8,13,21,34,55,89]
In [57]:
for number in fibs:
    print(number, end=",")
1,1,2,3,5,8,13,21,34,55,89,
In [58]:
for number in fibs:
    print(number**2, end=",")
1,1,4,9,25,64,169,441,1156,3025,7921,
In [59]:
for c in "this is some string":
    print(c, end=" ")
t h i s   i s   s o m e   s t r i n g 
In [60]:
points = [(0,0), (2,3), (1,1), (3,4)]
for p in points:
    print(p)
(0, 0)
(2, 3)
(1, 1)
(3, 4)
In [61]:
classroom = {"ankit":12, "ankita":34, "anshul":2, "akash":5}
In [62]:
for student in classroom:
    print(student, classroom[student])
ankit 12
ankita 34
anshul 2
akash 5
In [63]:
for student, num in classroom.items():
    print(student, num)
ankit 12
ankita 34
anshul 2
akash 5
In [64]:
for num in classroom.values():
    print(num)
12
34
2
5
In [65]:
for i in range(10):
    print(i, end=",")
0,1,2,3,4,5,6,7,8,9,
In [66]:
for i in range(3, 20, 3):
    print(i, end=",")
3,6,9,12,15,18,

problems

  • Write a function mysum to find sum of all numbers from given list
  • Write a function product to find product of all numbers from given list
  • Write a function factorial to find factorial of given number.
In [67]:
def mysum(numbers):
    s = 0
    for i in numbers:
        s = s + i
    return s
In [68]:
mysum([1,2,3,4])
Out[68]:
10
In [69]:
nums = [1,1,4,9,25,64,169,441,1156,3025,7921]
mysum(nums)
Out[69]:
12816
In [70]:
def product(nums):
    p = 1
    for item in nums:
        p = p*item
    return p
In [71]:
product([2,3,4,5])
Out[71]:
120
In [72]:
def factorial(n):
    return product(range(1, n+1))
In [73]:
factorial(5)
Out[73]:
120

lists splicing

In [76]:
fibs = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [77]:
fibs
Out[77]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [78]:
fibs[0]
Out[78]:
1
In [79]:
fibs[-1]
Out[79]:
89
In [81]:
fibs[2:4] #from 2nd index till 4th (excluding)
Out[81]:
[2, 3]
In [82]:
fibs[1:5]
Out[82]:
[1, 2, 3, 5]
In [84]:
fibs[1:] # drop 1
Out[84]:
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [86]:
fibs[2:] # drop 2
Out[86]:
[2, 3, 5, 8, 13, 21, 34, 55, 89]
In [87]:
fibs[:2]
Out[87]:
[1, 1]
In [88]:
fibs[:6]
Out[88]:
[1, 1, 2, 3, 5, 8]
In [89]:
fibs
Out[89]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [90]:
fibs[2:7:2]
Out[90]:
[2, 5, 13]
In [91]:
x = [1,1,1]
In [92]:
y = x
In [93]:
x.append(0)
In [94]:
x
Out[94]:
[1, 1, 1, 0]
In [95]:
y
Out[95]:
[1, 1, 1, 0]
In [96]:
z = fibs[:]
In [97]:
z
Out[97]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [98]:
fibs
Out[98]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [99]:
z.append(-1)
In [100]:
z
Out[100]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, -1]
In [101]:
fibs
Out[101]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [102]:
x = [1,1,1]
y = [1,1,1]
In [103]:
x == y
Out[103]:
True
In [104]:
x is y
Out[104]:
False
In [105]:
z = x
In [106]:
z is x
Out[106]:
True
In [107]:
filename
Out[107]:
'hello.py'
In [108]:
filename = "hello.py"
In [109]:
xlsfile = "hello.xls"
In [110]:
xlsfile.split(".")
Out[110]:
['hello', 'xls']
In [111]:
targz = "data.tar.gz"
In [112]:
targz.split(".")
Out[112]:
['data', 'tar', 'gz']
In [113]:
def findextension(filename):
    return filename.split(".")[-1]
In [114]:
findextension(targz)
Out[114]:
'gz'
In [115]:
findextension(xlsfile)
Out[115]:
'xls'
In [116]:
findextension("hello.py")
Out[116]:
'py'
In [117]:
fibs[:]
Out[117]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [118]:
fibs[::2]
Out[118]:
[1, 2, 5, 13, 34, 89]
In [119]:
fibs[::-1]
Out[119]:
[89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1]
In [120]:
word = "madam"
In [121]:
def isPalindrome(w):
    return w == w[::-1]
In [122]:
isPalindrome("madam")
Out[122]:
True
In [123]:
isPalindrome("hello")
Out[123]:
False
In [124]:
isPalindrome("121")
Out[124]:
True
In [125]:
len(fibs)
Out[125]:
11
In [126]:
fibs[100]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-126-aaafa5ea4530> in <module>
----> 1 fibs[100]

IndexError: list index out of range
In [127]:
fibs[1:100]
Out[127]:
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

mapping operation

In [128]:
empty = []
In [129]:
empty.append(1)
In [130]:
empty
Out[130]:
[1]

square every item in a list

In [131]:
def squarelist(numbers):
    sqr = []
    for n in numbers:
        s = n*n
        sqr.append(s)
    return sqr
In [132]:
squarelist(fibs)
Out[132]:
[1, 1, 4, 9, 25, 64, 169, 441, 1156, 3025, 7921]
In [133]:
squarelist(range(10))
Out[133]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

filtering

In [134]:
fibs
Out[134]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [136]:
def even(n):
    return n%2==0

def evens(numbers):
    e = []
    for item in numbers:
        if even(item):
            e.append(item)
    return e
In [137]:
evens(fibs)
Out[137]:
[2, 8, 34]

list comprehensions

In [138]:
import random
In [139]:
help(random.random)
Help on built-in function random:

random(...) method of random.Random instance
    random() -> x in the interval [0, 1).

In [140]:
random.random()
Out[140]:
0.8999356009016197
In [142]:
numbers = [ random.random() for i in range(10)]
In [143]:
numbers
Out[143]:
[0.7205590888972072,
 0.9778142789308142,
 0.5288316409270536,
 0.23844731506797756,
 0.8738900002640706,
 0.5141238730888505,
 0.5781873138055771,
 0.021540981993983466,
 0.12045382186339149,
 0.6560450293673615]
In [144]:
sqr = [n*n for n in numbers]
In [145]:
sqr
Out[145]:
[0.5192054005923734,
 0.9561207640809881,
 0.27966290444560016,
 0.05685712206312736,
 0.7636837325615373,
 0.2643233568798805,
 0.3343005698457089,
 0.0004640139052651199,
 0.014509123201497649,
 0.43039508055762227]
In [146]:
randomints = [int(10*random.random()) for i in range(10)]
In [147]:
randomints
Out[147]:
[7, 9, 1, 2, 0, 6, 8, 2, 9, 9]
In [148]:
[n*n for n in randomints]
Out[148]:
[49, 81, 1, 4, 0, 36, 64, 4, 81, 81]
In [149]:
[n for n in randomints if n%2==0]
Out[149]:
[2, 0, 6, 8, 2]
In [150]:
[n for n in randomints if n%2==1]
Out[150]:
[7, 9, 1, 9, 9]
In [152]:
[n for n in randomints if even(n)]
Out[152]:
[2, 0, 6, 8, 2]
In [153]:
def func(x):
    return x*x + 2*x + 1
In [154]:
from matplotlib.pyplot import plot
In [157]:
plot([func(i) for i in range(100)])
Out[157]:
[<matplotlib.lines.Line2D at 0x7fe084da8208>]
In [156]:
%matplotlib inline

problems

  • Write a function listpy to find list of all python files from given directory
    >>> listpy(os.getcwd())
    ['square.py', 'square1.py'...]
  • Write a function mtable to generate multiplication table of n
    >>> mtable(3)
    [3,6,9,....30]
In [158]:
[i for i in randomints if i%2==0]
Out[158]:
[2, 0, 6, 8, 2]
In [159]:
words = ["Hello", "Hi", "How", "When", "Why", "What"]
In [163]:
[w for w in words if w.startswith("H")] ##words starting with "H"
Out[163]:
['Hello', 'Hi', 'How']
In [161]:
words = ["Hello", "Hi", "How", "hoooo", "When", "Why", "What"]
In [164]:
[w for w in words if w.lower().startswith("h")] 
#words starting with h , case insensitive
Out[164]:
['Hello', 'Hi', 'How', 'hoooo']
In [1]:
def listpy(path):
    files = os.listdir(path)
    return [f for f in files if f.endswith(".py")]
In [2]:
def mtable(n):
    return [i*n for i in range(1, 11)]
In [3]:
mtable(5)
Out[3]:
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
In [4]:
for n in mtable(5):
    print(n)
5
10
15
20
25
30
35
40
45
50
In [6]:
tables = [mtable(i) for i in range(1,6)]
In [7]:
tables
Out[7]:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
 [3, 6, 9, 12, 15, 18, 21, 24, 27, 30],
 [4, 8, 12, 16, 20, 24, 28, 32, 36, 40],
 [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]
In [8]:
x = [[1,2], ["a","b"]]
In [9]:
len(x)
Out[9]:
2
In [10]:
x[0]
Out[10]:
[1, 2]
In [11]:
x[1]
Out[11]:
['a', 'b']
In [12]:
x[0][0]
Out[12]:
1
In [13]:
x[1][0]
Out[13]:
'a'
In [14]:
tables
Out[14]:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
 [3, 6, 9, 12, 15, 18, 21, 24, 27, 30],
 [4, 8, 12, 16, 20, 24, 28, 32, 36, 40],
 [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]
In [15]:
tables[0]
Out[15]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [16]:
tables[1]
Out[16]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
In [17]:
tables[4]
Out[17]:
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
In [21]:
tables[1][0]
Out[21]:
2
In [23]:
tables[1][1]
Out[23]:
4
In [24]:
tables[1][2]
Out[24]:
6
In [25]:
tables[0][1]
Out[25]:
2
In [26]:
tables[1][1]
Out[26]:
4
In [27]:
tables[2][1]
Out[27]:
6
In [31]:
[tables[i][3] for i in range(5)]
Out[31]:
[4, 8, 12, 16, 20]
In [32]:
def column(data, n):
    return [data[i][n] for i in range(len(data))]
In [33]:
column(tables, 0)
Out[33]:
[1, 2, 3, 4, 5]
In [34]:
column(tables, 4)
Out[34]:
[5, 10, 15, 20, 25]
In [35]:
tables
Out[35]:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
 [3, 6, 9, 12, 15, 18, 21, 24, 27, 30],
 [4, 8, 12, 16, 20, 24, 28, 32, 36, 40],
 [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]
In [36]:
def transpose(data):
    cols = len(data[0])
    return [column(data, i) for i in range(cols)]
In [37]:
transpose(tables)
Out[37]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]

problems

  • Write a function factors to find all factors of given number.
    >>> factors(6)
    [1,2,3,6]
    >>> factors(5)
    [1,5]
  • Write a function is_prime to find if given number is prime number or not. make use of fact that a prime number has only two factors, itself and 1!
  • Write a function to generate prime numbers less than n
In [38]:
def factors(n):
    return [i for i in range(1, n+1) if n%i==0]
In [39]:
def is_prime(n):
    return factors(n)==[1,n]
In [44]:
def primes(n):
    return [p for p in range(1,n) if is_prime(p)]
In [46]:
primes(50)
Out[46]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

iteration patterns

In [47]:
p = primes(20)
In [48]:
p
Out[48]:
[2, 3, 5, 7, 11, 13, 17, 19]
In [49]:
for i in p:
    print(i, end=",")
2,3,5,7,11,13,17,19,
In [52]:
for i in reversed(p): #should be used only in for loop
    print(i, end=",")
19,17,13,11,7,5,3,2,
In [51]:
p[::-1]
Out[51]:
[19, 17, 13, 11, 7, 5, 3, 2]
In [55]:
for index, num in enumerate(p): #should be used only in loop
    print(index, num)
0 2
1 3
2 5
3 7
4 11
5 13
6 17
7 19
In [56]:
first = ["Elsa", "David", "Alice"]
lastname = ["Frozen", "Hacker", "Wonder"]
In [58]:
for name, surname in zip(first, lastname):
    print(name, surname)
Elsa Frozen
David Hacker
Alice Wonder
In [59]:
z = zip(first, lastname)
In [60]:
z
Out[60]:
<zip at 0x7f4402eb8d08>
In [61]:
rp = reversed(p)
In [62]:
for i in p:
    print(i, end=",")
2,3,5,7,11,13,17,19,
In [63]:
for i in rp:
    print(i, end=",")
19,17,13,11,7,5,3,2,
In [64]:
for i in p:
    print(i, end=",")
2,3,5,7,11,13,17,19,
In [65]:
for i in rp:
    print(i, end=",")
In [66]:
x,y = (2,3)
In [67]:
x
Out[67]:
2
In [68]:
y
Out[68]:
3
In [69]:
x,y = [4,5]
In [70]:
x
Out[70]:
4
In [71]:
y
Out[71]:
5
In [73]:
for x,y,z in zip(range(10), range(10), range(10)):
    print(x,y,z)
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 9
In [74]:
list(zip(range(5), ["one","two","three","four","five"]))
Out[74]:
[(0, 'one'), (1, 'two'), (2, 'three'), (3, 'four'), (4, 'five')]

string formating

In [75]:
s = "Wizard of oz is {} and can do {}"
In [76]:
s.format("python", "computation")
Out[76]:
'Wizard of oz is python and can do computation'
In [77]:
"Wizard of oz is {1} and can do {0}".format("python", "pccoe student")
Out[77]:
'Wizard of oz is pccoe student and can do python'
In [78]:
"Wizard of oz is {person} and can do {task}".format(person="python", task="computation")
Out[78]:
'Wizard of oz is python and can do computation'
In [79]:
for i in range(1,11):
    print(i, i*i, i*i*i)
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
In [81]:
for i in range(1,11):
    line = "{:2d} {:3d} {:4d}".format(i, i*i, i*i*i)
    print(line)
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
In [83]:
ans = "Answer is 42"
In [84]:
ans.ljust(30)
Out[84]:
'Answer is 42                  '
In [85]:
ans.rjust(30)
Out[85]:
'                  Answer is 42'
In [86]:
ans.center(30)
Out[86]:
'         Answer is 42         '

problem

  • Write a function print_triangle which will print a triangle of * of base n.
    >>> print_triangle(5)
        * 
       * *
      * * *
     * * * *
    * * * * *

Take home assignment

  • Write a function pascal to generate pascal traingle as a 2D list.
    >>> pascal(4)
    [[1],[1,1],[1,2,1],[1,3,3,1]]
  • Write a function print_pascal to print pascal triangle of base n.
    >>> print_pascal(4)
            1
          1   1
        1   2   1
      1   3   3   1
    `
  • Write a function dirtree to generate tree structure of directory
    >>> dirtree(os.getcwd())
    .
    ├── day1.html
    ├── day1.ipynb
    ├── day2.html
    ├── day2.ipynb
    ├── hello.py
    ├── helloworld.py
    ├── Makefile
    ├── push
    ├── __pycache__
    │   ├── square1.cpython-37.pyc
    │   ├── square2.cpython-37.pyc
    │   └── square.cpython-37.pyc
    ├── python_basic
    │   └── Untitled.ipynb
    ├── square1.py
    ├── square2.py
    └── square.py
In [87]:
"*"*5
Out[87]:
'*****'
In [88]:
mtable("*")
Out[88]:
['*',
 '**',
 '***',
 '****',
 '*****',
 '******',
 '*******',
 '********',
 '*********',
 '**********']
In [ ]: