Basic Python Training at Arcesium - Day 3

Apr 15-18, 2019 Vikrant Patil

These notes are available online at http://notes.pipal.in/2019/arcesium_basic_apr/day3.html

© Pipal Academy LLP

Day 1 | Day 2 | Day 3 | Day 4

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

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

In [3]:
def circlearea(radius=1.0): #default paramenter.
    return 3.14*radius*radius
In [5]:
circlearea() # radius is taken as 1.0 as default value
Out[5]:
3.14
In [6]:
print(1)
print(2) # end = new line
1
2
In [7]:
print(1, end=",")
print(2, end=",")
1,2,

problems

  • write a function minumum2 to minimum of two number.

    >>> minimum2(2,3)
    2
  • write a function minimum3 to find minimum from three numbers

    >>> minimum3(3,1,5)
    1
In [9]:
if 2 > 3:
    print(2)
else:
    print(3)
3
In [10]:
2 > 4
Out[10]:
False
In [11]:
2 <= 4
Out[11]:
True
In [12]:
2 >= 4
Out[12]:
False
In [13]:
2 == 3
Out[13]:
False
In [16]:
def min2(x, y):
    if x < y:
        return x
    else:
        return y
In [17]:
min2(5, 6)
Out[17]:
5
In [19]:
def min3(x, y, z):
    return min2( min2(x, y), z)
In [24]:
def min3(x, y, z):
    if x < y and x <z:
        return x
    elif y < x and y < z:
        return y
    else:
        return z

recap for loop

In [21]:
primes = [2, 3, 5, 7, 11, 13, 17, 19]
In [23]:
for p in primes:
    print(p, p*p)
2 4
3 9
5 25
7 49
11 121
13 169
17 289
19 361
In [25]:
for p in primes:
    print(str(p).rjust(2), str(p*p).rjust(3))
 2   4
 3   9
 5  25
 7  49
11 121
13 169
17 289
19 361
In [27]:
for c in "This string with some text in it":
    print(c, end=",")
T,h,i,s, ,s,t,r,i,n,g, ,w,i,t,h, ,s,o,m,e, ,t,e,x,t, ,i,n, ,i,t,
In [28]:
for item in (1, 2, 3, 4, 5, 6):
    print(item, end=" ")
1 2 3 4 5 6 
In [29]:
help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

In [30]:
print(1, 2, 3)
1 2 3
In [31]:
print(1, 2, 3, sep="_")
1_2_3

Example ls.py

In [41]:
%%file ls.py
import sys, os

def ls(dirname=None):
    if dirname is None:
        dirname = os.getcwd()
        
    files = os.listdir(dirname)
    
    for file in files:
        print(file)
        
def main():
    if len(sys.argv)>1:
        ls(sys.argv[1])
    else:
        ls()
        
    
if __name__ == "__main__":
    print("*"*5, sys.argv)
    main()
Overwriting ls.py
In [42]:
!python ls.py 
***** ['ls.py']
.ipynb_checkpoints
rearrangemax.py
push
day1.ipynb
mymath.py
addmany.py
mymath3.py
day2.ipynb
day2.html
python_training
mymath1.py
add1.py
mymath6.py
mymath2.py
day3.ipynb
day3.html
Makefile
palindrom.py
__pycache__
mymath4.py
add.py
mymath5.py
day1.html
ls.py
In [37]:
from ls import ls
In [38]:
ls()
.ipynb_checkpoints
rearrangemax.py
push
day1.ipynb
mymath.py
addmany.py
mymath3.py
day2.ipynb
day2.html
python_training
mymath1.py
add1.py
mymath6.py
mymath2.py
day3.ipynb
day3.html
Makefile
palindrom.py
__pycache__
mymath4.py
add.py
mymath5.py
day1.html
ls.py
In [39]:
ls("/home")
mohini
lost+found
vikrant
In [40]:
!python ls.py /home/vikrant/trainings/
***** ['ls.py', '/home/vikrant/trainings/']
2018
day5.org~
day5.org
2017
2019
nakul

list comprehensions

In [43]:
primes
Out[43]:
[2, 3, 5, 7, 11, 13, 17, 19]
In [44]:
def square(x):
    return x*x

s = []
for p in primes:
    s.append(square(p))
print(s)
[4, 9, 25, 49, 121, 169, 289, 361]
In [45]:
[p*p for p in primes]
Out[45]:
[4, 9, 25, 49, 121, 169, 289, 361]
In [48]:
for i in range(7):
    print(primes[i]*primes[i], end=",")
4,9,25,49,121,169,289,361,
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-48-df450c42e569> in <module>
      1 for i in range(9):
----> 2     print(primes[i]*primes[i], end=",")

IndexError: list index out of range
In [47]:
len(primes)
Out[47]:
8
In [49]:
[p*p*p for p in primes]
Out[49]:
[8, 27, 125, 343, 1331, 2197, 4913, 6859]
In [50]:
[n*n for n in range(20) if n%2==0]
Out[50]:
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
In [51]:
[n*n for n in range(20) if n%2==0]
Out[51]:
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
In [52]:
[1, 2, 3, 4]
Out[52]:
[1, 2, 3, 4]
In [53]:
col1 = [1,1,1]
col2 = [2, 2, 2]
col3 = [3, 3, 3]
table = [col1, col2, col3]
In [54]:
table
Out[54]:
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
In [55]:
tables = [[n*i for i in range(1, 11)] for n in range(1, 6)]
In [56]:
tables
Out[56]:
[[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 [57]:
def evens(seq):
    return [e for e in seq if e%2==0]
In [58]:
evens([1, 23,2, 3,5, 45, 66, 87])
Out[58]:
[2, 66]
In [59]:
def factors(n):
    return [f for f in range(1, n+1) if n%f==0]
In [60]:
factors(5)
Out[60]:
[1, 5]
In [61]:
factors(6)
Out[61]:
[1, 2, 3, 6]
In [62]:
factors(7)
Out[62]:
[1, 7]
In [63]:
factors(9)
Out[63]:
[1, 3, 9]
In [64]:
factors(10)
Out[64]:
[1, 2, 5, 10]
In [65]:
def is_prime(p):
    return factors(p)==[1,p]
In [66]:
is_prime(5)
Out[66]:
True
In [67]:
is_prime(10)
Out[67]:
False
In [68]:
def primes(n):
    return [p for p in range(1, n+1) if is_prime(p)]
In [70]:
primes(50)
Out[70]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

problems

  • Generate first 50 natural numbers
  • Generate all numbers divisible by 7 and less than 100 using list comprehensions
  • find sum of all multiples of 7 or 11 less than 1000
In [71]:
[i for i in range(1, 51)]
Out[71]:
[1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 13,
 14,
 15,
 16,
 17,
 18,
 19,
 20,
 21,
 22,
 23,
 24,
 25,
 26,
 27,
 28,
 29,
 30,
 31,
 32,
 33,
 34,
 35,
 36,
 37,
 38,
 39,
 40,
 41,
 42,
 43,
 44,
 45,
 46,
 47,
 48,
 49,
 50]
In [73]:
[i for i in range(1, 100) if i%7==0]
Out[73]:
[7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98]
In [75]:
sum([i for i in range(1000) if i%7==0 or i%11==0])
Out[75]:
110110

iteration patterns

In [76]:
for p in primes(20):
    print(p)
2
3
5
7
11
13
17
19
In [77]:
primes_ = primes(20)
In [78]:
for p in primes_:
    print(p)
2
3
5
7
11
13
17
19
In [79]:
for p in reversed(primes_):
    print(p)
19
17
13
11
7
5
3
2
In [83]:
rp = reversed(primes_) #rp is not a list, it is iterator in rversed way to original list, to be used only once
In [81]:
for p in rp:
    print(p)
19
17
13
11
7
5
3
2
In [82]:
for p in rp:
    print(p)
In [84]:
[p for p in reversed(primes_)] # new copy in reversed way
Out[84]:
[19, 17, 13, 11, 7, 5, 3, 2]
In [87]:
primes_[::-1] # new copy in reversed way
Out[87]:
[19, 17, 13, 11, 7, 5, 3, 2]
In [88]:
primes_
Out[88]:
[2, 3, 5, 7, 11, 13, 17, 19]
In [94]:
primes_.reverse() # this changes original data, it is not copy
In [95]:
primes_
Out[95]:
[19, 17, 13, 11, 7, 5, 3, 2]
In [96]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In [98]:
poem = """
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
In [99]:
lines = poem.split("\n")
In [100]:
lines
Out[100]:
['',
 'The Zen of Python, by Tim Peters',
 '',
 'Beautiful is better than ugly.',
 'Explicit is better than implicit.',
 'Simple is better than complex.',
 'Complex is better than complicated.',
 'Flat is better than nested.',
 'Sparse is better than dense.',
 'Readability counts.',
 "Special cases aren't special enough to break the rules.",
 'Although practicality beats purity.',
 'Errors should never pass silently.',
 'Unless explicitly silenced.',
 'In the face of ambiguity, refuse the temptation to guess.',
 'There should be one-- and preferably only one --obvious way to do it.',
 "Although that way may not be obvious at first unless you're Dutch.",
 'Now is better than never.',
 'Although never is often better than *right* now.',
 "If the implementation is hard to explain, it's a bad idea.",
 'If the implementation is easy to explain, it may be a good idea.',
 "Namespaces are one honking great idea -- let's do more of those!",
 '']
In [103]:
for i, line in enumerate(lines): # enumerate iterates with two items , index and the object from seq
    print(i, line)
0 
1 The Zen of Python, by Tim Peters
2 
3 Beautiful is better than ugly.
4 Explicit is better than implicit.
5 Simple is better than complex.
6 Complex is better than complicated.
7 Flat is better than nested.
8 Sparse is better than dense.
9 Readability counts.
10 Special cases aren't special enough to break the rules.
11 Although practicality beats purity.
12 Errors should never pass silently.
13 Unless explicitly silenced.
14 In the face of ambiguity, refuse the temptation to guess.
15 There should be one-- and preferably only one --obvious way to do it.
16 Although that way may not be obvious at first unless you're Dutch.
17 Now is better than never.
18 Although never is often better than *right* now.
19 If the implementation is hard to explain, it's a bad idea.
20 If the implementation is easy to explain, it may be a good idea.
21 Namespaces are one honking great idea -- let's do more of those!
22 
In [104]:
x, y = 2, 3
In [105]:
for i, line in enumerate(lines): # enumerate iterates with two items , index and the object from seq
    print(i+1, line)
1 
2 The Zen of Python, by Tim Peters
3 
4 Beautiful is better than ugly.
5 Explicit is better than implicit.
6 Simple is better than complex.
7 Complex is better than complicated.
8 Flat is better than nested.
9 Sparse is better than dense.
10 Readability counts.
11 Special cases aren't special enough to break the rules.
12 Although practicality beats purity.
13 Errors should never pass silently.
14 Unless explicitly silenced.
15 In the face of ambiguity, refuse the temptation to guess.
16 There should be one-- and preferably only one --obvious way to do it.
17 Although that way may not be obvious at first unless you're Dutch.
18 Now is better than never.
19 Although never is often better than *right* now.
20 If the implementation is hard to explain, it's a bad idea.
21 If the implementation is easy to explain, it may be a good idea.
22 Namespaces are one honking great idea -- let's do more of those!
23 
In [107]:
first = ["Elisa", "Elsa", "Alice"]
second = ["Hacker", "Frozen", "Wonder"]

zip interates over more than one sequences at a time giving one item from each sequence.

In [108]:
for x,y in zip(first, second): 
    print(x, y)
Elisa Hacker
Elsa Frozen
Alice Wonder
In [109]:
first = ["Elisa", "Elsa", "Alice"]
second = ["Hacker", "Frozen", "Wonder"]
third = ["A", "B", "C", "D"]
In [110]:
for x, y, z in zip(first, second, third):
    print(x, y, z)
Elisa Hacker A
Elsa Frozen B
Alice Wonder C
In [111]:
for x, y, z in zip(first, second, third[1:]):
    print(x, y, z)
Elisa Hacker B
Elsa Frozen C
Alice Wonder D

Working with files

In [112]:
%%file data.txt
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Writing data.txt
In [113]:
with open("data.txt") as f:
    print(f.read())
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

In [114]:
f = open("data.txt")
f.read()
f.close()
In [116]:
with open("data.txt") as data:
    for line in data:
        print(line, end="") # because line contains its own new line
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In [118]:
with open("data.txt") as data:
    print(data.readline(), end="")
    print(data.readline(), end="")
    print(data.readline(), end="")
    print(data.readline(), end="")
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
In [119]:
range(5)
Out[119]:
range(0, 5)
In [120]:
for i in range(5):
    print(i)
0
1
2
3
4
In [130]:
f = open("data.txt")
In [131]:
f
Out[131]:
<_io.TextIOWrapper name='data.txt' mode='r' encoding='UTF-8'>
In [132]:
[l.strip() for l in f]
Out[132]:
['The Zen of Python, by Tim Peters',
 '',
 'Beautiful is better than ugly.',
 'Explicit is better than implicit.',
 'Simple is better than complex.',
 'Complex is better than complicated.',
 'Flat is better than nested.',
 'Sparse is better than dense.',
 'Readability counts.',
 "Special cases aren't special enough to break the rules.",
 'Although practicality beats purity.',
 'Errors should never pass silently.',
 'Unless explicitly silenced.',
 'In the face of ambiguity, refuse the temptation to guess.',
 'There should be one-- and preferably only one --obvious way to do it.',
 "Although that way may not be obvious at first unless you're Dutch.",
 'Now is better than never.',
 'Although never is often better than *right* now.',
 "If the implementation is hard to explain, it's a bad idea.",
 'If the implementation is easy to explain, it may be a good idea.',
 "Namespaces are one honking great idea -- let's do more of those!"]
In [133]:
f.close()
In [134]:
f = open("data.txt")
lines = f.readlines()
f.close()
In [135]:
lines
Out[135]:
['The Zen of Python, by Tim Peters\n',
 '\n',
 'Beautiful is better than ugly.\n',
 'Explicit is better than implicit.\n',
 'Simple is better than complex.\n',
 'Complex is better than complicated.\n',
 'Flat is better than nested.\n',
 'Sparse is better than dense.\n',
 'Readability counts.\n',
 "Special cases aren't special enough to break the rules.\n",
 'Although practicality beats purity.\n',
 'Errors should never pass silently.\n',
 'Unless explicitly silenced.\n',
 'In the face of ambiguity, refuse the temptation to guess.\n',
 'There should be one-- and preferably only one --obvious way to do it.\n',
 "Although that way may not be obvious at first unless you're Dutch.\n",
 'Now is better than never.\n',
 'Although never is often better than *right* now.\n',
 "If the implementation is hard to explain, it's a bad idea.\n",
 'If the implementation is easy to explain, it may be a good idea.\n',
 "Namespaces are one honking great idea -- let's do more of those!\n"]

examples

lets build unix utilities cat, head, wc

In [138]:
%%file cat.py
import sys

def cat(filename):
    with open(filename) as f:
        print(f.read())

        
if __name__ == "__main__":
    cat(sys.argv[1])
Overwriting cat.py
In [139]:
!python cat.py data.txt
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

In [140]:
print(range(5))
range(0, 5)
In [141]:
r = range(5)
In [142]:
r[0]
Out[142]:
0
In [145]:
%%file head.py
import sys

def head(filename, n):
    with open(filename) as f:
        for i in range(n):
            print(f.readline(), end="")
            
if __name__ == "__main__":
    head(sys.argv[1], int(sys.argv[2]))
Overwriting head.py
In [146]:
!python head.py data.txt 5
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
In [147]:
%%file wc.py
import sys

def charcount(file):
    with open(file) as f:
        return len(f.read())
    
def linecount(file):
    with open(file) as f:
        return len(f.readlines())
    
def wordcount(file):
    with open(file) as f:
        return len(f.read().split())
    
    
if __name__ == "__main__":
    f = sys.argv[1]
    print(linecount(f), wordcount(f), charcount(f), f)
Writing wc.py
In [148]:
!python wc.py data.txt
21 144 857 data.txt

Writing files

In [153]:
with open("numbers.txt", "w") as f: # r (read) , w (write), a (append)
    nums = [1, 2, 3, 4]
    words = ["one", "two", "three", "four"]

    for n, w in zip(nums, words):
        f.write(str(n) + " " + w) # as this is text mode, you can write only string i.e. text!
        f.write("\n")
        
In [154]:
!python cat.py numbers.txt
1 one
2 two
3 three
4 four

In [155]:
with open("numbers.txt", "a") as f: # a (append)
    nums = [1, 2, 3, 4]
    words = ["one", "two", "three", "four"]

    for n, w in zip(nums, words):
        f.write(str(n) + " " + w) # as this is text mode, you can write only string i.e. text!
        f.write("\n")
        
In [156]:
!python cat.py numbers.txt
1 one
2 two
3 three
4 four
1 one
2 two
3 three
4 four

Example CSV parser

In [157]:
tables
Out[157]:
[[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 [160]:
def writeCSV(data, filename):
    with open(filename, "w") as f:
        for row in data:
            textrow = ",".join(map(str, row))
            f.write(textrow + "\n")
In [161]:
writeCSV(tables, "tables.csv")
In [162]:
!python cat.py tables.csv
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 [169]:
f = open("data.txt", "w")
help(f)
In [166]:
help(f.writelines)
Help on built-in function writelines:

writelines(lines, /) method of _io.TextIOWrapper instance

In [170]:
f.writelines(["a","b","c"])
In [171]:
f.close()
In [174]:
!python cat.py data.txt
abc
In [175]:
def csvparser(csvfile):
    with open(csvfile) as f:
        d = []
        for line in f:
            d.append(line.strip().split())
        return d
In [176]:
csvparser("tables.csv")
Out[176]:
[['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 [184]:
def csvparser(csvfile):
    def to_int(items):
        return list(map(int, items))
    
    with open(csvfile) as f:
        return [to_int(line.strip().split(",")) for line in f]
        
In [185]:
csvparser("tables.csv")
Out[185]:
[[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]]

Working with dictionary

In [186]:
stock = {
    "name":"Infosys", 
    "value": 1001,
    "exchange":"BSE",
    "gain":5.5
}
In [187]:
stock['name']
Out[187]:
'Infosys'
In [188]:
stock.get("name")
Out[188]:
'Infosys'
In [189]:
stock.get("date")
In [190]:
stock['date']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-190-3e4f146e84fb> in <module>
----> 1 stock['date']

KeyError: 'date'
In [191]:
stock.get("date", "17 Apr 19")
Out[191]:
'17 Apr 19'
In [192]:
stock
Out[192]:
{'name': 'Infosys', 'value': 1001, 'exchange': 'BSE', 'gain': 5.5}
In [193]:
del stock['name']
In [194]:
stock
Out[194]:
{'value': 1001, 'exchange': 'BSE', 'gain': 5.5}
In [195]:
stock['name'] = "Infosys"
In [196]:
stock
Out[196]:
{'value': 1001, 'exchange': 'BSE', 'gain': 5.5, 'name': 'Infosys'}
In [197]:
%%file inputs.txt
param1 45
maxgain 5
startyear 2018
month March
Writing inputs.txt
In [198]:
def parseinputs(filename):
    with open(filename) as f:
        inputs = {}
        for line in f:
            key, value = line.strip().split()
            inputs[key] = value
        return inputs
In [199]:
parseinputs("inputs.txt")
Out[199]:
{'param1': '45', 'maxgain': '5', 'startyear': '2018', 'month': 'March'}
In [200]:
{i:i for i in range(5)}
Out[200]:
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
In [201]:
inputs = parseinputs("inputs.txt")
In [202]:
inputs
Out[202]:
{'param1': '45', 'maxgain': '5', 'startyear': '2018', 'month': 'March'}

looping on dictionary

In [203]:
for item in inputs:
    print(item)
param1
maxgain
startyear
month
In [204]:
for k,v in inputs.items():
    print(k , v)
param1 45
maxgain 5
startyear 2018
month March
In [205]:
for v in inputs.values():
    print(v)
45
5
2018
March
In [206]:
list("hello")
Out[206]:
['h', 'e', 'l', 'l', 'o']
In [208]:
dict([("a",1), ("b",2), ("c",3)])
Out[208]:
{'a': 1, 'b': 2, 'c': 3}
In [209]:
dict(zip(first, second))
Out[209]:
{'Elisa': 'Hacker', 'Elsa': 'Frozen', 'Alice': 'Wonder'}
In [212]:
{1, 2, 2} # set
Out[212]:
{1, 2}
In [213]:
{"a":1, "b":2} # dictionary
Out[213]:
{'a': 1, 'b': 2}

Example

In [214]:
%%file words.txt
one 
one two
one two three
one two three four
one two three four five
one two three four six
one two three seven six
one two eight seven six
one nine eight seven six
ten nine eight seven
ten nine eight
ten nine
ten
Writing words.txt
In [215]:
words = ["one", "one", "two", "three", "three", "three"]
In [216]:
words.count("one")
Out[216]:
2
In [217]:
uniquewords = set(words)
In [218]:
uniquewords
Out[218]:
{'one', 'three', 'two'}
In [219]:
for w in uniquewords:
    print(w, words.count(w))
three 3
one 2
two 1
In [220]:
freq = {}
for w in words:
    if w in freq:
        freq[w] += 1
    else:
        freq[w] = 1
In [221]:
freq
Out[221]:
{'one': 2, 'two': 1, 'three': 3}
In [222]:
freq = {}
for w in words:
    freq[w] = freq.get(w, 0) + 1
In [223]:
freq
Out[223]:
{'one': 2, 'two': 1, 'three': 3}
In [229]:
def get_words(filename):
    with open(filename) as f:
        return f.read().split()
    
def wordfreq(words):
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return freq
In [230]:
words = get_words("words.txt")
In [231]:
freq = wordfreq(words)
In [232]:
freq
Out[232]:
{'one': 9,
 'two': 7,
 'three': 5,
 'four': 3,
 'five': 1,
 'six': 4,
 'seven': 4,
 'eight': 4,
 'nine': 4,
 'ten': 4}
In [234]:
for w, f in freq.items():
    print(w.rjust(7), f)
    one 9
    two 7
  three 5
   four 3
   five 1
    six 4
  seven 4
  eight 4
   nine 4
    ten 4
In [237]:
def get_freq(r):
    return r[1]

for w, f in sorted(freq.items(), key=get_freq):
    print(w.rjust(7), f)
   five 1
   four 3
    six 4
  seven 4
  eight 4
   nine 4
    ten 4
  three 5
    two 7
    one 9
In [238]:
for w, f in sorted(freq.items(), key=get_freq):
    print(w.rjust(7), f*"*")
   five *
   four ***
    six ****
  seven ****
  eight ****
   nine ****
    ten ****
  three *****
    two *******
    one *********

classes

In [239]:
%%file bank.py

balance = 0

def get_balance():
    return balance

def deposit(amount):
    global balance
    balance += amount
    
def withdraw(amount):
    global balance
    balance -= amount
    
Writing bank.py
In [240]:
import bank
In [241]:
bank.get_balance()
Out[241]:
0
In [242]:
bank.deposit(100)
In [243]:
bank.get_balance()
Out[243]:
100
In [244]:
%%file bank1.py

def make_account():
    return {"balance":0}

def get_balance(account):
    return account['balance']

def deposit(account, amount):
    account['balance'] += amount
    
def withdraw(account, amount):
    account['balance'] -= amount
Writing bank1.py
In [245]:
import bank1
In [246]:
a1 = bank1.make_account()
In [247]:
a2 = bank1.make_account()
In [248]:
bank1.deposit(a1, 100)
In [249]:
bank1.deposit(a2, 1000)
In [250]:
bank1.get_balance(a1)
Out[250]:
100
In [251]:
bank1.get_balance(a2)
Out[251]:
1000
In [252]:
class BankAccount:
    
    def __init__(self):
        self.balance = 0
        
    def get_balance(self):
        return self.balance
    
    def deposit(self, amount):
        self.balance += amount
        
    def withdraw(self, amount):
        self.balance -= amount
        
    
    
In [253]:
a3 = BankAccount()
a4 = BankAccount()
In [254]:
type(a3)
Out[254]:
__main__.BankAccount
In [255]:
type(a4)
Out[255]:
__main__.BankAccount
In [256]:
a3.get_balance()
Out[256]:
0
In [257]:
a3.deposit(200)
In [258]:
a3.get_balance()
Out[258]:
200
In [259]:
a3.withdraw(20)
In [260]:
a3.get_balance()
Out[260]:
180
In [263]:
class BankAccount:
    
    def __init__(self, name):
        self.balance = 0
        self.name = name
        
    def get_balance(self):
        return self.balance
    
    def deposit(self, amount):
        self.balance += amount
        
    def withdraw(self, amount):
        self.balance -= amount
        
    def get_name(self):
        return self.name
In [264]:
a5 = BankAccount("Python")
In [265]:
a5.get_balance()
Out[265]:
0
In [266]:
a5.get_name()
Out[266]:
'Python'
In [ ]: