Basic Python Training at Arcesium - Day 2

Oct 25-31, 2018 Vikrant Patil

These notes are available online at http://notes.pipal.in/2018/arcesium-basic-oct/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/

Functions and environment

In [4]:
x = 10
def func(x):
    x = 2*x 
    print("x: inside func =", x)
    return x

func(30)
print("x: outside func = ", x)
x: inside func = 60
x: outside func =  10
In [3]:
print(1, "hello", "world!", ".....",end=",")
print(2, "hello", "world!", ".....",)
1 hello world! .....,2 hello world! .....
In [6]:
func(x)
print("x: outside func=",x)
x: inside func = 20
x: outside func= 10
In [7]:
def appendone(data):
    data.append(1)
    return data
In [9]:
l = [1,2,3,4,5]
appendone(l)
print(l)
[1, 2, 3, 4, 5, 1]
In [11]:
x = func(30)
print(x)
x: inside func = 60
60
In [12]:
x
Out[12]:
60
In [13]:
def xadder(y):
    return x+y
In [14]:
xadder(20)
Out[14]:
80
In [16]:
def xmodify():
    
    x = x + 30
    print("x: inside xmodify = ", x )

x = 50
xmodify()
print(x)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-16-3b00788e39f3> in <module>()
      6 
      7 x = 50
----> 8 xmodify()
      9 print(x)

<ipython-input-16-3b00788e39f3> in xmodify()
      2 def xmodify():
      3 
----> 4     x = x + 30
      5     print("x: inside xmodify = ", x )
      6 

UnboundLocalError: local variable 'x' referenced before assignment
In [19]:
def xmodify():
    global x
    x = x + 30
    print("x: inside xmodify = ", x )

x = 50
xmodify()
print(x)
x: inside xmodify =  80
80
In [20]:
def xmodify():
    global x
    x = x + 30
    print("x: inside xmodify = ", x )

del x
xmodify()
print(x)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-20-64f62625b5f1> in <module>()
      6 
      7 del x
----> 8 xmodify()
      9 print(x)

<ipython-input-20-64f62625b5f1> in xmodify()
      2 def xmodify():
      3     global x
----> 4     x = x + 30
      5     print("x: inside xmodify = ", x )
      6 

NameError: name 'x' is not defined

problem

  • Write a function make_sentence to make sentence out of list of wrods.
>>> make_sentence(["Hi", "there", ",", "how", "are", "you", "doing?"])
'Hi there ,  how are you doing?'
  • Write a function to make word from list of charectrs!
>>> make_word(["p","y","t","h","o","n"])
'python'
In [21]:
def make_sentence(words):
    return " ".join(words)
In [22]:
def make_word(chars):
    return "".join(chars)
In [23]:
make_sentence(["Hello","world","pyhton"])
Out[23]:
'Hello world pyhton'
In [24]:
make_word(["p","y","t","h","o","n"])
Out[24]:
'python'
In [25]:
make_word(["1","2","3"])
Out[25]:
'123'
In [26]:
def make_int(digits):
    strnum = make_word(digits)
    return int(strnum)
In [28]:
x = make_int(["1","2","3"])
In [29]:
x
Out[29]:
123
In [30]:
x + 2
Out[30]:
125
In [31]:
"123" + 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-302b50a9c00e> in <module>()
----> 1 "123" + 2

TypeError: must be str, not int

function inside a function

In [32]:
def make_adder(x):
    
    def adder(y):
        return x+y
    
    return adder
    
In [33]:
adder5 = make_adder(5)
In [34]:
print(adder5)
<function make_adder.<locals>.adder at 0x7fa96c203048>
In [35]:
adder5(10)
Out[35]:
15
In [36]:
adder5(20)
Out[36]:
25
In [38]:
adder10 = make_adder(10)
In [39]:
adder10(12)
Out[39]:
22
In [40]:
adder5(12)
Out[40]:
17

modules

In [41]:
import os
In [42]:
import math as m
In [43]:
os.getcwd()
Out[43]:
'/home/vikrant/trainings/2018/arcesium-basic-oct'
In [47]:
os.getlogin()
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-47-64defab13146> in <module>()
----> 1 os.getlogin()

OSError: [Errno 25] Inappropriate ioctl for device
In [48]:
os.listdir()
Out[48]:
['.ipynb_checkpoints',
 'push',
 'day1.ipynb',
 'day2.ipynb',
 'day2.html',
 'Untitled.html',
 'day3.ipynb',
 'day3.html',
 'Makefile',
 'day1.html']
In [49]:
os.listdir("/tmp/")
Out[49]:
['Temp-a21992e3-047a-437b-9de2-7080c5b00b70',
 '.XIM-unix',
 'systemd-private-3270fe7df28f4ceb9d3c568a70b9f733-rtkit-daemon.service-bCxaoC',
 '.font-unix',
 'ssh-0fmS1RKCc14x',
 'config-err-d1AaiV',
 'systemd-private-3270fe7df28f4ceb9d3c568a70b9f733-colord.service-5xPWT2',
 '.ICE-unix',
 '.X11-unix',
 '.X0-lock',
 '.Test-unix',
 'mintUpdate']
In [50]:
os.path.exists("/tmp/")
Out[50]:
True
In [51]:
os.path.exists("c:\\")
Out[51]:
False
In [52]:
os.path.getsize("day1.ipynb")
Out[52]:
77805
In [53]:
"\t"
Out[53]:
'\t'
In [54]:
os.path.abspath("day1.html")
Out[54]:
'/home/vikrant/trainings/2018/arcesium-basic-oct/day1.html'
In [56]:
contents = os.listdir()
In [57]:
contents
Out[57]:
['.ipynb_checkpoints',
 'push',
 'day1.ipynb',
 'day2.ipynb',
 'day2.html',
 'Untitled.html',
 'day3.ipynb',
 'day3.html',
 'Makefile',
 'day1.html']
In [58]:
max(contents, key=len)
Out[58]:
'.ipynb_checkpoints'
In [59]:
max(contents, key=os.path.getsize)
Out[59]:
'day1.html'

problem

  • Write a function to count files in current directory
In [60]:
def countfiles():
    return len(os.listdir())
In [61]:
countfiles()
Out[61]:
10
In [62]:
def countfiles(dirpath):
    return len(os.listdir(dirpath))
In [63]:
countfiles(".")
Out[63]:
10
In [64]:
#os.path.join("c:", "")
os.path.join("/home","vikrant", "training")
Out[64]:
'/home/vikrant/training'
In [65]:
os.path.isfile("day1.html")
Out[65]:
True
In [66]:
os.path.isdir("/tmp")
Out[66]:
True
In [67]:
import numpy
In [68]:
import math
In [69]:
math.pi
Out[69]:
3.141592653589793
In [70]:
math.sin(math.pi)
Out[70]:
1.2246467991473532e-16
In [71]:
math.ceil(2.3)
Out[71]:
3
In [72]:
os.mkdir("test")
In [73]:
os.listdir()
Out[73]:
['.ipynb_checkpoints',
 'push',
 'day1.ipynb',
 'day2.ipynb',
 'day2.html',
 'Untitled.html',
 'day3.ipynb',
 'day3.html',
 'Makefile',
 'test',
 'day1.html']
In [75]:
%%file mymodule.py
def hello(name):
    print("Hello", name)
    
Writing mymodule.py
In [76]:
import mymodule
In [77]:
mymodule.hello("pyhton")
Hello pyhton
In [78]:
from mymodule import hello
In [79]:
hello("Arcesium")
Hello Arcesium
In [80]:
%%file bank.py

balance = 0

def get_balance():
    return balance
Writing bank.py
In [81]:
import bank
In [82]:
bank.balance
Out[82]:
0
In [83]:
bank.get_balance()
Out[83]:
0
In [84]:
bank.balance = 100
In [85]:
bank.get_balance()
Out[85]:
100
In [86]:
import sys
In [88]:
%%file square.py

import sys

def square(x):
    return x*x


print(sys.argv)
num = int(sys.argv[1])
sqr = square(num)
print(sqr)
Overwriting square.py
In [89]:
!python square.py 67
['square.py', '67']
4489
In [90]:
%%file add.py
import sys

def add(x,y):
    return x+y

a = int(sys.argv[1])
b = int(sys.argv[2])

print(add(a,b))
Writing add.py
In [92]:
!python add.py 1 300
301
In [96]:
%%file echo.py
import sys

def echo(expr):
    print(expr)

expr = sys.argv[1]

print(sys.argv)
echo(expr)
Overwriting echo.py
In [97]:
!python echo.py hello world
['echo.py', 'hello', 'world']
hello
In [98]:
!python echo.py hello\ world
['echo.py', 'hello world']
hello world
In [99]:
!python echo.py "hello world"
['echo.py', 'hello world']
hello world
In [100]:
!echo hello echo this all
hello echo this all
In [101]:
digits = [1,2,3,4,5,6]
In [102]:
digits[:]
Out[102]:
[1, 2, 3, 4, 5, 6]
In [103]:
digits[1:]
Out[103]:
[2, 3, 4, 5, 6]
In [104]:
%%file echo.py
import sys

def echo(expr):
    print(expr)

expr = " ".join(sys.argv[1:])

echo(expr)
Overwriting echo.py
In [105]:
!python echo.py hello echo this statement
hello echo this statement

condtions

In [106]:
"hel" in "hello"
Out[106]:
True
In [107]:
"alice" in {"alice":1, "alex":2}
Out[107]:
True
In [108]:
1 in [1,2,3,4,5]
Out[108]:
True
In [109]:
filename = "hello.py"
if ".py" in filename:
    print("python")
python
In [110]:
filename = "hello.exe"
if ".py" in filename:
    print("python")
else:
    print("something else")
something else
In [111]:
filename = "hello.exe"
if ".py" in filename:
    print("python")
elif ".exe" in filename:
    print("executable")
elif ".xlsx" in filename:
    print("excelsheet")
else:
    pass
    
executable
In [113]:
%%file backup.py
import sys

def delete_old(path):
    print("Deleted old data")
    
def copy_new(src, dest):
    print("Copying new data to backup location")
    
src = sys.argv[1]
dest = sys.argv[2]

delete_old(dest)
copy_new(src, dest)
Overwriting backup.py
In [114]:
import backup
Deleted old data
Copying new data to backup location
In [119]:
%%file backup1.py
import sys

def delete_old(path):
    print("Deleted old data")
    
def copy_new(src, dest):
    print("Copying new data to backup location")
    
src = sys.argv[1]
dest = sys.argv[2]

print(__name__)
#delete_old(dest)
#copy_new(src, dest)
Overwriting backup1.py
In [116]:
import backup1
backup1
In [117]:
!python backup1.py src dest
__main__
In [123]:
%%file backup2.py
import sys

def delete_old(path):
    print("Deleted old data")
    
def copy_new(src, dest):
    print("Copying new data to backup location")
    

if __name__ == "__main__":
    src = sys.argv[1]
    dest = sys.argv[2]
    delete_old(dest)
    copy_new(src, dest)
Overwriting backup2.py
In [124]:
import backup2
In [122]:
!python backup2.py /home/vikrant/trainings/ /tmp/
Deleted old data
Copying new data to backup location

problem

  • write a function min2 to find minimum from two numbers
  • write a function min3 to find minimum from threee numbers
In [125]:
2 > 3
Out[125]:
False
In [126]:
2 <= 3
Out[126]:
True
In [127]:
2 == 2
Out[127]:
True
In [128]:
def min2(x, y):
    if x < y:
        return x
    else:
        return y
In [129]:
def min3(x, y, z):
    return min2(min2(x,y),z)
In [130]:
min3(34,56,1)
Out[130]:
1
In [132]:
math.sqrt(min2(3,56) + sum([1,2,3]))
Out[132]:
3.0
In [133]:
 3 * 100 + 20
Out[133]:
320

loops

In [134]:
n = 10
while n > 0:
    print(n, end=",")
    n = n - 1 # n -= 1
10,9,8,7,6,5,4,3,2,1,
In [147]:
def sum_(seq):
    s = 0
    pos = len(seq)
    while pos > 0:
        pos = pos-1
        print(pos, end=",")
        s = s + seq[pos]
    return s
In [148]:
sum_([12,12,34,1,2,1])
5,4,3,2,1,0,
Out[148]:
62
In [149]:
sum([12,12,34,1,2,1])
Out[149]:
62
In [152]:
digits = [0,1,2,3,4,5]
for digit in digits:
    s = digit*digit
    print(digit)
0
1
2
3
4
5
In [153]:
for i in digits:
    print(i)
0
1
2
3
4
5
In [154]:
people = ["Anand", "David", "Alex", "Alia", "Elsa"]
for person in people:
    print(person)
Anand
David
Alex
Alia
Elsa
In [155]:
for name in people:
    print(name)
Anand
David
Alex
Alia
Elsa
In [156]:
for c in "some random statement":
    print(c,end=",")
s,o,m,e, ,r,a,n,d,o,m, ,s,t,a,t,e,m,e,n,t,
In [157]:
morepeople = ["girish", "ashok", "ankit", "aniket", "dua"]
In [158]:
def commonfrom(collection1, collection2):
    common = []
    for person in collection1:
        if person in collection2:
            common.append(person)
    return common
In [159]:
commonfrom(morepeople, people)
Out[159]:
[]
In [160]:
morepeople.append("Anand")
In [161]:
commonfrom(morepeople, people)
Out[161]:
['Anand']
In [162]:
!ls
add.py	    bank.py	day2.ipynb  Makefile	 square.py
backup1.py  day1.html	day3.html   mymodule.py  test
backup2.py  day1.ipynb	day3.ipynb  push	 Untitled.html
backup.py   day2.html	echo.py     __pycache__

problem

  • Write a module ls.py which lists prints files from current directory
In [164]:
print(os.listdir())
['.ipynb_checkpoints', 'push', 'day1.ipynb', 'backup2.py', 'day2.ipynb', 'echo.py', 'day2.html', 'Untitled.html', 'square.py', 'mymodule.py', 'backup1.py', 'day3.ipynb', 'bank.py', 'backup.py', 'day3.html', 'Makefile', 'test', '__pycache__', 'add.py', 'day1.html']
In [166]:
%%file ls.py
import os
def ls():
    for file in os.listdir():
        print(file)
        
if __name__ == "__main__":
    ls()
Overwriting ls.py
In [167]:
!python ls.py
.ipynb_checkpoints
push
day1.ipynb
backup2.py
day2.ipynb
echo.py
day2.html
Untitled.html
square.py
mymodule.py
backup1.py
day3.ipynb
bank.py
backup.py
day3.html
Makefile
test
__pycache__
add.py
day1.html
ls.py

problem

  • write a function double which doubles every item from a list and returns new list
  • Write a function which squares every item from a list and returns it.
  • Write a function which finds product of all elements from a list.
  • make use of product to write a function to find factorial of given number
In [168]:
for i in range(10):
    print(i)
0
1
2
3
4
5
6
7
8
9
In [ ]: