Basic Python Training at Arcesium - Day 1

Sep 23-24, 2019 Vikrant Patil

These notes are available online at http://notes.pipal.in/2019/arcesium_basic_sep/day1.html

© Pipal Academy LLP

Day 1 | Day 2

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

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

In [1]:
2 + 3
Out[1]:
5

Basics

# Header1
## Header2
### Header3

Header1

Header2

Header3

Basic Data types

There are integers

In [2]:
2 + 3
Out[2]:
5
In [3]:
2 -3 
Out[3]:
-1
In [4]:
3*3
Out[4]:
9
In [5]:
3 **2
Out[5]:
9
In [9]:
2**100 #power
Out[9]:
1267650600228229401496703205376
In [8]:
5/2 #real division
Out[8]:
2.5
In [11]:
5 // 2 # integer division operator
Out[11]:
2

There are floats

In [12]:
2.3 + 5.5
Out[12]:
7.8
In [13]:
3.4*3
Out[13]:
10.2
In [14]:
3.14**2
Out[14]:
9.8596

Text data

In [15]:
"This is text data"
Out[15]:
'This is text data'
In [16]:
'This is also a string'
Out[16]:
'This is also a string'
In [17]:
s = "Python training going on!"
In [18]:
s
Out[18]:
'Python training going on!'
In [19]:
print(s)
Python training going on!
In [20]:
print(2)
2
In [21]:
2
Out[21]:
2
In [22]:
s = "232323"
In [23]:
s
Out[23]:
'232323'
In [24]:
print(s)
232323
In [25]:
sentence = "He said, 'I am fine!'"
In [26]:
print(sentence)
He said, 'I am fine!'
In [27]:
multiline = """one
two
three
"""
In [28]:
print(multiline)
one
two
three

In [29]:
multiline
Out[29]:
'one\ntwo\nthree\n'
In [30]:
multi = "Line1\nLine2\n"
In [36]:
windowspath = "c:\\Program Files\\Anaconda"
In [37]:
windowspath
Out[37]:
'c:\\Program Files\\Anaconda'
In [38]:
print(windowspath)
c:\Program Files\Anaconda
In [39]:
star = "*"
In [40]:
star + star
Out[40]:
'**'
In [41]:
star*5
Out[41]:
'*****'
In [42]:
sentence
Out[42]:
"He said, 'I am fine!'"
In [43]:
sentence[0]
Out[43]:
'H'
In [44]:
sentence[-1]
Out[44]:
"'"
In [45]:
sentence[4]
Out[45]:
'a'

->  0  1  2  3  4  5
    p  y  t  h  o  n
   -6 -5 -4 -3 -2 -1<---
In [46]:
s = "python"
In [47]:
sentence[2]
Out[47]:
' '
In [48]:
sentence[5]
Out[48]:
'i'
In [49]:
sentence[0]
Out[49]:
'H'
In [50]:
sentence
Out[50]:
"He said, 'I am fine!'"

Higher level data types

List ordered items

In [51]:
numbers = [1, 2, 3, 4, 5, 6]
In [52]:
numbers[0]
Out[52]:
1
In [53]:
numbers[-1]
Out[53]:
6
In [54]:
numbers[1]
Out[54]:
2
In [55]:
numbers[2]
Out[55]:
3
In [56]:
matrix = [[1, 1, 1],[2, 2, 2],[3, 3, 3]]
In [57]:
matrix
Out[57]:
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
In [58]:
matrix[0]
Out[58]:
[1, 1, 1]
In [59]:
matrix[-1]
Out[59]:
[3, 3, 3]
In [60]:
matrix[0][0]
Out[60]:
1
In [61]:
mixed = ["name", "age", 1,  [1, 1, 1]]
In [62]:
mixed
Out[62]:
['name', 'age', 1, [1, 1, 1]]
In [63]:
mixed[-1]
Out[63]:
[1, 1, 1]
In [64]:
mixed[2]
Out[64]:
1
In [65]:
numbers
Out[65]:
[1, 2, 3, 4, 5, 6]
In [66]:
digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [67]:
digits[2:5] # start at index 2 and end at 5 (exluded)
Out[67]:
[2, 3, 4]
In [69]:
digits[3:7:2] # start at index 3 end at 7 (excluded) at interval of 2
Out[69]:
[3, 5]

tuples sibling of list

In [70]:
point = (0, 0, 1)
In [71]:
point[0]
Out[71]:
0
In [72]:
point[-1]
Out[72]:
1
In [74]:
point[1:3]
Out[74]:
(0, 1)
In [75]:
numbers
Out[75]:
[1, 2, 3, 4, 5, 6]
In [76]:
numbers[0] = 0
In [77]:
numbers
Out[77]:
[0, 2, 3, 4, 5, 6]
In [78]:
point[0] = -1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-78-43292da72da0> in <module>
----> 1 point[0] = -1

TypeError: 'tuple' object does not support item assignment
  • Strings, tuples are immutable objects. Once created , they can not be modified.
In [79]:
sentence[0] = "M"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-79-1168265a405f> in <module>
----> 1 sentence[0] = "M"

TypeError: 'str' object does not support item assignment

Dictionary

key value pairs

In [80]:
stock = {"name":"Arcesium", "ticker":"arc", "value":2000}
In [81]:
stock
Out[81]:
{'name': 'Arcesium', 'ticker': 'arc', 'value': 2000}
In [83]:
stock['name']
Out[83]:
'Arcesium'
In [84]:
stock['value']
Out[84]:
2000
In [85]:
stock['value'] = 2500
In [86]:
stock
Out[86]:
{'name': 'Arcesium', 'ticker': 'arc', 'value': 2500}

set

unique unordered values

In [89]:
s = {"one", "two", "two", "three"}
In [90]:
s
Out[90]:
{'one', 'three', 'two'}

boolean

In [91]:
yes = True
no = False

Nothing

In [92]:
None
In [93]:
n = None
In [94]:
n
In [95]:
print(n)
None

Functions

In [96]:
numbers
Out[96]:
[0, 2, 3, 4, 5, 6]
In [101]:
len(numbers) # length of list
Out[101]:
6
In [102]:
len(sentence) # length of a string
Out[102]:
21
In [103]:
len(s) # length of a set
Out[103]:
3
In [104]:
len(stock) # length of a dictionary
Out[104]:
3
In [106]:
len(point) # length of tuple
Out[106]:
3
In [107]:
n = "32324"
In [108]:
int(n)
Out[108]:
32324
In [109]:
float(n)
Out[109]:
32324.0
In [110]:
str(23244343)
Out[110]:
'23244343'

problem

  • find number digits in 2**1000
In [111]:
2**1000
Out[111]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
In [112]:
str(2**1000)
Out[112]:
'10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376'
In [113]:
len(str(2**1000))
Out[113]:
302
In [114]:
digits
Out[114]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [115]:
range(10)
Out[115]:
range(0, 10)
In [116]:
list(range(10))
Out[116]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [118]:
list(range(1,20,3))
Out[118]:
[1, 4, 7, 10, 13, 16, 19]
In [123]:
list(range(5)) # end
Out[123]:
[0, 1, 2, 3, 4]
In [121]:
list(range(3, 10)) # start , end
Out[121]:
[3, 4, 5, 6, 7, 8, 9]
In [122]:
list(range(2, 15, 3)) # start, end, interval
Out[122]:
[2, 5, 8, 11, 14]
In [124]:
sum(numbers)
Out[124]:
20
In [125]:
max(numbers)
Out[125]:
6
In [126]:
min(numbers)
Out[126]:
0
In [127]:
max(sentence)
Out[127]:
's'

custom function

In [128]:
def add(x, y):
    s = x + y 
    return s

add(4,5)
Out[128]:
9
In [129]:
def count_digits(n):
    return len(str(n))
In [130]:
count_digits(2**100)
Out[130]:
31
In [133]:
def empty():
    pass # a function should have atleast one line it. it can be pass too!
In [132]:
def hello():
  File "<ipython-input-132-ae3321f449c2>", line 1
    def hello():
                ^
SyntaxError: unexpected EOF while parsing

problem

  • Write a simple function twice which just doubles the number
  • Write a function twice1 to print twice value of a number

then try

>>> twice(twice(3))
>>> twice1(twice1(3))
In [134]:
def twice(x):
    return 2*x

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

<ipython-input-134-78f3a63b6689> in twice1(x)
      3 
      4 def twice1(x):
----> 5     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
In [137]:
twice1(3)
6
In [138]:
twice(3)
Out[138]:
6
In [139]:
r = twice(3)
In [140]:
r
Out[140]:
6
In [141]:
r1 = twice1(3)
6
In [143]:
print(r1)
None
In [144]:
print(2)
2
In [145]:
x = print(2)
2
In [146]:
x
In [147]:
print(x)
None

Every function has to return a value. if not returned explicitly, it returns None

More about Functions

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


def sumofsquare(x, y):
    return square(x) + square(y)


def cube(x):
    return x*x*x

def sumofcube(x, y):
    return cube(x) + cube(y)
In [150]:
del a
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-150-84acad089b3e> in <module>
----> 1 del a

NameError: name 'a' is not defined
In [151]:
a = 5
In [152]:
def add(x, y):
    return x+y
In [153]:
add
Out[153]:
<function __main__.add(x, y)>
In [154]:
aliasadd = add
In [155]:
aliasadd
Out[155]:
<function __main__.add(x, y)>
In [156]:
add(5, 6)
Out[156]:
11
In [157]:
aliasadd(5, 6)
Out[157]:
11
In [158]:
sumofsquare(5,4)
Out[158]:
41
In [159]:
def sumof(f, x, y):
    return f(x) + f(y)
In [160]:
sumof(square, 5, 4)
Out[160]:
41
In [161]:
sumof(cube, 5, 6)
Out[161]:
341

max, min, sorted

In [162]:
words = ["one","two","three","four", "five","six"]
In [163]:
max(words)
Out[163]:
'two'
In [164]:
max(words, key=len)
Out[164]:
'three'
In [165]:
min(words, key=len)
Out[165]:
'one'
In [166]:
sorted(words, key=len)
Out[166]:
['one', 'two', 'six', 'four', 'five', 'three']
In [167]:
sorted(words)
Out[167]:
['five', 'four', 'one', 'six', 'three', 'two']
In [168]:
records = [
    ("TATA", 200.0, 5.5),
    ("INFY", 2000.0, -5),
    ("RELIANCE", 1505.5, 50.0),
    ("HCL", 1200, 70.5)
]
In [169]:
def get_value(r):
    return r[1]

def get_gain(r):
    return r[2]
In [170]:
max(records, key=get_value)
Out[170]:
('INFY', 2000.0, -5)
In [171]:
max(records, key=get_gain)
Out[171]:
('HCL', 1200, 70.5)
In [173]:
sorted(records, key=get_value, reverse=True)
Out[173]:
[('INFY', 2000.0, -5),
 ('RELIANCE', 1505.5, 50.0),
 ('HCL', 1200, 70.5),
 ('TATA', 200.0, 5.5)]
In [174]:
sorted(records, key=get_gain)
Out[174]:
[('INFY', 2000.0, -5),
 ('TATA', 200.0, 5.5),
 ('RELIANCE', 1505.5, 50.0),
 ('HCL', 1200, 70.5)]

Higher order functions

In [175]:
def make_logger(logtype):
    
    def logger(msg):
        print(logtype + ":", msg)
        
    return logger
In [176]:
info = make_logger("INFO")
In [177]:
error = make_logger("ERROR")
warning = make_logger("WARN")
In [178]:
info
Out[178]:
<function __main__.make_logger.<locals>.logger(msg)>
In [179]:
info("Just for your information")
INFO: Just for your information
In [180]:
warning("Something is not right, be careful!")
WARN: Something is not right, be careful!
In [181]:
error("Surely things went wrong!")
ERROR: Surely things went wrong!
In [182]:
def make_adder(x):
    
    def adder(y):
        return x+y
    
    return adder
In [183]:
adder5 = make_adder(5)
In [184]:
adder5(35)
Out[184]:
40

lambda expressions

In [185]:
def make_adder(x):
    return lambda y: x+y
In [186]:
adder9 = make_adder(9)
In [187]:
adder9(5)
Out[187]:
14
In [188]:
add = lambda x, y: x+y
In [189]:
add(3,4)
Out[189]:
7
In [190]:
square = lambda x: x*x
In [191]:
square(3)
Out[191]:
9
In [192]:
numbers = [-42,3,5,-3,5]
In [193]:
max(numbers, key=lambda x:x*x)
Out[193]:
-42
In [194]:
records
Out[194]:
[('TATA', 200.0, 5.5),
 ('INFY', 2000.0, -5),
 ('RELIANCE', 1505.5, 50.0),
 ('HCL', 1200, 70.5)]
In [195]:
max(records, key=lambda r: r[1])
Out[195]:
('INFY', 2000.0, -5)
In [196]:
max(records, key=lambda r:r[2])
Out[196]:
('HCL', 1200, 70.5)

methods from objects

In [197]:
text = "Wizard of oz is python 3"
In [198]:
text.upper()
Out[198]:
'WIZARD OF OZ IS PYTHON 3'
In [199]:
text
Out[199]:
'Wizard of oz is python 3'
In [200]:
text.lower()
Out[200]:
'wizard of oz is python 3'
In [201]:
text.capitalize()
Out[201]:
'Wizard of oz is python 3'
In [202]:
text.count(" ")
Out[202]:
5
In [203]:
text.replace("python", "scala")
Out[203]:
'Wizard of oz is scala 3'
In [204]:
text
Out[204]:
'Wizard of oz is python 3'
In [205]:
text[0] = "A"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-205-35158a75baa9> in <module>
----> 1 text[0] = "A"

TypeError: 'str' object does not support item assignment
In [206]:
text.split()
Out[206]:
['Wizard', 'of', 'oz', 'is', 'python', '3']
In [207]:
text.split("is")
Out[207]:
['Wizard of oz ', ' python 3']
In [208]:
text.split() # white spaces, which includes multiple spaces , tabs, newlines
Out[208]:
['Wizard', 'of', 'oz', 'is', 'python', '3']
In [209]:
words = text.split()
In [210]:
words
Out[210]:
['Wizard', 'of', 'oz', 'is', 'python', '3']
In [211]:
text_trailing = " Wizard of oz is python 3       \n"
In [212]:
print(text_trailing)
 Wizard of oz is python 3       

In [213]:
text_trailing
Out[213]:
' Wizard of oz is python 3       \n'
In [214]:
text_trailing.split()
Out[214]:
['Wizard', 'of', 'oz', 'is', 'python', '3']
In [215]:
words
Out[215]:
['Wizard', 'of', 'oz', 'is', 'python', '3']
In [216]:
",".join(words)
Out[216]:
'Wizard,of,oz,is,python,3'
In [217]:
text_trailing = '   Wizard,of,oz,is,python,3     '
In [218]:
text_trailing.split(",")
Out[218]:
['   Wizard', 'of', 'oz', 'is', 'python', '3     ']
In [219]:
text_trailing.strip().split(",")
Out[219]:
['Wizard', 'of', 'oz', 'is', 'python', '3']
In [220]:
text
Out[220]:
'Wizard of oz is python 3'
In [221]:
text.startswith("Wizard")
Out[221]:
True
In [222]:
text.endswith("2.7")
Out[222]:
False
In [223]:
text.center(50)
Out[223]:
'             Wizard of oz is python 3             '
In [224]:
text.ljust(50)
Out[224]:
'Wizard of oz is python 3                          '
In [225]:
text.rjust(50)
Out[225]:
'                          Wizard of oz is python 3'
In [226]:
text.count("i")
Out[226]:
2

methods from lists

In [227]:
numbers
Out[227]:
[-42, 3, 5, -3, 5]
In [228]:
numbers.count(5)
Out[228]:
2
In [229]:
numbers.count(3)
Out[229]:
1
In [230]:
numbers.count(0)
Out[230]:
0
In [231]:
numbers.append(7)
In [232]:
numbers
Out[232]:
[-42, 3, 5, -3, 5, 7]
In [233]:
x = numbers.append(8)
In [234]:
print(x)
None
In [235]:
numbers
Out[235]:
[-42, 3, 5, -3, 5, 7, 8]
In [236]:
x = numbers.pop()
In [237]:
x
Out[237]:
8
In [238]:
numbers
Out[238]:
[-42, 3, 5, -3, 5, 7]
In [239]:
empty = []
In [240]:
empty.append(0)
In [241]:
empty.append(0)
In [242]:
empty
Out[242]:
[0, 0]
In [243]:
numbers
Out[243]:
[-42, 3, 5, -3, 5, 7]
In [244]:
numbers.insert(0, -45)
In [245]:
numbers
Out[245]:
[-45, -42, 3, 5, -3, 5, 7]
In [246]:
numbers.sort()
In [247]:
numbers
Out[247]:
[-45, -42, -3, 3, 5, 5, 7]
In [248]:
nums = [-42, 3, 5, -3, 5, 7]
In [249]:
sorted(nums)
Out[249]:
[-42, -3, 3, 5, 5, 7]
In [250]:
nums
Out[250]:
[-42, 3, 5, -3, 5, 7]
In [251]:
numbers
Out[251]:
[-45, -42, -3, 3, 5, 5, 7]
In [252]:
numbers.reverse()
In [253]:
numbers
Out[253]:
[7, 5, 5, 3, -3, -42, -45]
In [254]:
numbers.extend([1, 2, 3, 4])
In [255]:
numbers
Out[255]:
[7, 5, 5, 3, -3, -42, -45, 1, 2, 3, 4]
In [256]:
numbers + [1, 2, 3]
Out[256]:
[7, 5, 5, 3, -3, -42, -45, 1, 2, 3, 4, 1, 2, 3]

tuples

In [257]:
t = (1, 1, 1, 0)
In [258]:
t.count(1)
Out[258]:
3
In [259]:
t.index(0)
Out[259]:
3

modules

In [260]:
import os
In [261]:
import math
In [262]:
import math as m
In [263]:
math.pi
Out[263]:
3.141592653589793
In [264]:
m.pi
Out[264]:
3.141592653589793
In [265]:
os.getcwd() # current working directory
Out[265]:
'/home/vikrant/trainings/2019/arcesium_basic_sep'
In [266]:
os.listdir()
Out[266]:
['Makefile',
 'day1.html',
 '.ipynb_checkpoints',
 'day2.ipynb',
 'day1.ipynb',
 'push',
 'day2.html']
In [269]:
os.listdir("/home/vikrant/trainings/")
Out[269]:
['day5.org~', 'day5.org', '2018', 'nakul', '2017', '2019']

problem

  • Write a function countfiles which returns number of files in given directory/folder
In [270]:
def countfiles(path):
    return len(os.listdir(path))
In [271]:
countfiles(".")
Out[271]:
7
In [272]:
os.path.exists("/home/vikrant")
Out[272]:
True
In [273]:
os.path.getsize("day1.ipynb")
Out[273]:
77226
In [275]:
def biggestfile(path):
    files = os.listdir(path)
    return max(files, key=os.path.getsize)
In [286]:
biggestfile(".")
Out[286]:
'day1.html'

conditions

if cond1:
   "here if cond1 is True"
elif cond2:
   "here if cond2 is True"
elif cond3:
   "here if cond3 is True"
else:
   "if none of above condtions are True"
In [288]:
text
Out[288]:
'Wizard of oz is python 3'
In [289]:
"python" in text
Out[289]:
True
In [290]:
"scala" not in text
Out[290]:
True
In [291]:
text.endswith("hello")
Out[291]:
False
In [292]:
2 ==3 
Out[292]:
False
In [293]:
2 != 3
Out[293]:
True
In [294]:
2 > 3
Out[294]:
False
In [295]:
2 >=3
Out[295]:
False
In [296]:
3 < 5
Out[296]:
True
In [297]:
3 <= 5
Out[297]:
True
In [298]:
stock
Out[298]:
{'name': 'Arcesium', 'ticker': 'arc', 'value': 2500}
In [299]:
"name" in stock ## check in keys of dictionary
Out[299]:
True
In [300]:
"gain" in stock
Out[300]:
False
In [301]:
"value" in stock
Out[301]:
True
In [302]:
numbers
Out[302]:
[7, 5, 5, 3, -3, -42, -45, 1, 2, 3, 4]
In [303]:
7 in numbers
Out[303]:
True
In [304]:
42 not in numbers
Out[304]:
True
In [306]:
s #set
Out[306]:
{'one', 'three', 'two'}
In [307]:
"one" in s
Out[307]:
True
In [308]:
stock.keys()
Out[308]:
dict_keys(['name', 'ticker', 'value'])
In [309]:
stock.values()
Out[309]:
dict_values(['Arcesium', 'arc', 2500])
In [310]:
"arc" in stock.values()
Out[310]:
True
In [311]:
a = "arc"
In [312]:
b = a
In [313]:
a is b
Out[313]:
True

Various ways to look for help

  • on jupyter notebook/lab a? , it will help for a object
  • on interpreter help(a)
  • on terminal pydoc str
In [318]:
help(text.lower)
Help on built-in function lower:

lower() method of builtins.str instance
    Return a copy of the string converted to lowercase.

In [319]:
def filetype(filename):
    """
    Finds filetype for given filename. 
    it supports following extensions .txt, .py, .exe
    """
    
    if filename.endswith(".py"):
        return "python"
    elif filename.endswith(".txt"):
        return "text"
    elif filename.endswith(".exe"):
        return "executable"
    else:
        return "unknown"
In [320]:
help(filetype)
Help on function filetype in module __main__:

filetype(filename)
    Finds filetype for given filename. 
    it supports following extensions .txt, .py, .exe

In [321]:
filetype("hello.py")
Out[321]:
'python'

custom modules

In [322]:
%%file mymodule.py

data = 42

def square(x):
    return x*x

def say_hello(name):
    print("Hello", name)
Writing mymodule.py

add location of this module in system variable PYTHONPATH PYTHONPATH=location;

current directory is always in python path

In [323]:
import mymodule
In [324]:
mymodule.data
Out[324]:
42
In [325]:
mymodule.say_hello("Arcesium")
Hello Arcesium

Scripts

In [326]:
%%file add.py
import sys

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


print(sys.argv)
Writing add.py
In [335]:
!python add.py 2 3 4 5 6
['add.py', '2', '3', '4', '5', '6']
In [328]:
!python add.py 
['add.py']
In [329]:
%%file add1.py
import sys

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


add(int(sys.argv[1]), int(sys.argv[2]))
Writing add1.py
In [330]:
!python add1.py 2 4
In [331]:
%%file add2.py
import sys

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


print(add(int(sys.argv[1]), int(sys.argv[2])))
Writing add2.py
In [333]:
!python add2.py 4 5
9

Question: How do I take multiple arguments

revisiting list

In [337]:
digits = list(range(10))
In [338]:
digits
Out[338]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [340]:
digits[2:6]
Out[340]:
[2, 3, 4, 5]
In [343]:
digits[2:] # drop frist 2
Out[343]:
[2, 3, 4, 5, 6, 7, 8, 9]
In [344]:
digits[:5] # take first 5
Out[344]:
[0, 1, 2, 3, 4]
In [345]:
digits[2:7:2]
Out[345]:
[2, 4, 6]
In [347]:
digits[:] # copy
Out[347]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [349]:
digits[::-1] # reverse
Out[349]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
In [350]:
sum(digits)
Out[350]:
45
In [351]:
sum(['1','2','3'])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-351-f5b0a9351cb5> in <module>
----> 1 sum(['1','2','3'])

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [355]:
list(map(int, ['1','2','3'])) ##apply int function to every item in the list
Out[355]:
[1, 2, 3]
In [356]:
%%file add3.py
"""
add3 is a script which can add any number of numbers given from command line
"""
import sys

s = sum(map(int, sys.argv[1:]))

print(s)
Writing add3.py
In [357]:
!python add3.py 2 3 4 2 3
14
In [358]:
from add2 import add
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-358-4f2cd49b2c08> in <module>
----> 1 from add2 import add

~/trainings/2019/arcesium_basic_sep/add2.py in <module>
      5 
      6 
----> 7 print(add(int(sys.argv[1]), int(sys.argv[2])))

ValueError: invalid literal for int() with base 10: '-f'
In [359]:
%%file add21.py
import sys

def add(x, y):
    return x+y
Writing add21.py
In [360]:
from add21 import add
In [361]:
%%file add22.py
import sys

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

print(__name__)
Writing add22.py
In [362]:
!python add22.py
__main__
In [363]:
import add22
add22
In [364]:
%%file add23.py
import sys

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

if __name__ == "__main__":
    print(add(int(sys.argv[1]), int(sys.argv[2])))
Writing add23.py
In [365]:
!python add23.py 2 4
6
In [366]:
from add23 import add
In [367]:
add(5, 6)
Out[367]:
11

Environment

In [368]:
def foo(x):
    
    x = 10
    
a = 12

foo(a)
print(a)
12
In [370]:
def foo(x):
    print("before", x)
    x = 10
    print("after", x)
    
a = 12

foo(a)
print(a)
before 12
after 10
12
In [373]:
def bar():
    print("local", z)
    
    
z = 13
bar()
print("global", z)
local 13
global 13
In [374]:
def bar():
    print("local", z)
    z = 10
    
z = 13
bar()
print("global", z)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-374-b0f49054701d> in <module>
      4 
      5 z = 13
----> 6 bar()
      7 print("global", z)

<ipython-input-374-b0f49054701d> in bar()
      1 def bar():
----> 2     print("local", z)
      3     z = 10
      4 
      5 z = 13

UnboundLocalError: local variable 'z' referenced before assignment
In [375]:
def bar():
    global z
    print("before", z)
    z = 10
    
z = 13
bar()
print("global", z)
before 13
global 10

while loop

In [376]:
a, b = 1, 2
In [377]:
a
Out[377]:
1
In [378]:
b
Out[378]:
2
In [379]:
b , a = a, b
In [382]:
def print_fibonaci(n):
    curr, prev = 1, 1
    while curr < n:
        print(curr, end=",")
        curr, prev = curr + prev, curr
        
In [383]:
print_fibonaci(100)
1,2,3,5,8,13,21,34,55,89,

for loops

In [384]:
for c in "this sentence":
    print(c, end=",")
t,h,i,s, ,s,e,n,t,e,n,c,e,
In [385]:
for num in [1, 2, 3, 4, 5]:
    print(num, end=",")
1,2,3,4,5,
In [386]:
nums
Out[386]:
[-42, 3, 5, -3, 5, 7]
In [387]:
for n in nums:
    print(n , n*n)
-42 1764
3 9
5 25
-3 9
5 25
7 49
In [388]:
for s in stock:
    print(s, stock[s])
name Arcesium
ticker arc
value 2500
In [390]:
s = set(numbers)
In [391]:
s
Out[391]:
{-45, -42, -3, 1, 2, 3, 4, 5, 7}
In [392]:
for item in s:
    print(item, end=",")
1,2,3,4,5,7,-45,-42,-3,
In [393]:
for i in range(5):
    print(i, end=" ")
0 1 2 3 4 
In [394]:
sqrs = map(lambda x:x*x, range(1, 11))
In [395]:
sqrs
Out[395]:
<map at 0x7fbb93f9b668>
In [396]:
for i in sqrs:
    print(i, end=",")
1,4,9,16,25,36,49,64,81,100,
In [397]:
range(4)
Out[397]:
range(0, 4)

iteration patterns

In [398]:
for i in range(5):
    print(i, end=",")
0,1,2,3,4,
In [400]:
list(range(5,0))
Out[400]:
[]
In [401]:
l = [1,2,3,4]
In [402]:
#l.reverse() this is one way, but you loose original data
In [403]:
for i in l[::-1]:
    print(i, end=",")
4,3,2,1,
In [404]:
for i in reversed(l):
    print(i, end=",")
4,3,2,1,
In [405]:
l
Out[405]:
[1, 2, 3, 4]
In [406]:
lr = reversed(l)
In [407]:
for i in lr:
    print(i, end=",")
4,3,2,1,
In [408]:
for i in lr:
    print(i, end=",")
In [409]:
words
Out[409]:
['Wizard', 'of', 'oz', 'is', 'python', '3']
In [410]:
for w in words:
    print(w, end=" ")
Wizard of oz is python 3 
In [411]:
for i, w in enumerate(words):
    print(i, w)
0 Wizard
1 of
2 oz
3 is
4 python
5 3
In [412]:
for i, w in enumerate(words, 100):
    print(i, w)
100 Wizard
101 of
102 oz
103 is
104 python
105 3
In [415]:
for i, w in enumerate(words):
    print(i)
0
1
2
3
4
5
In [416]:
a, b = 1,2
In [417]:
a = 2,3
In [418]:
a
Out[418]:
(2, 3)
In [419]:
for i in enumerate(words):
    print(i)
(0, 'Wizard')
(1, 'of')
(2, 'oz')
(3, 'is')
(4, 'python')
(5, '3')
In [420]:
for i,j,k in enumerate(words):
    print(i)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-420-e529d31277ba> in <module>
----> 1 for i,j,k in enumerate(words):
      2     print(i)

ValueError: not enough values to unpack (expected 3, got 2)
In [421]:
enumerate?
In [423]:
for i in enumerate(words):
    print(i)
(0, 'Wizard')
(1, 'of')
(2, 'oz')
(3, 'is')
(4, 'python')
(5, '3')
In [424]:
names = ["Elsa", "Alice", "Elisa"]
surnames = ["Frozen", "Wonder", "Hacker"]
In [425]:
zip(names, surnames)
Out[425]:
<zip at 0x7fbba41309c8>
In [426]:
list(zip(names, surnames))
Out[426]:
[('Elsa', 'Frozen'), ('Alice', 'Wonder'), ('Elisa', 'Hacker')]
In [427]:
for n,s in zip(names, surnames):
    print(n , s)
Elsa Frozen
Alice Wonder
Elisa Hacker
In [428]:
names = ["Elsa", "Alice", "Elisa", "Alex"]
surnames = ("Frozen", "Wonder", "Hacker")

for n,s in zip(names, surnames):
    print(n,s)
Elsa Frozen
Alice Wonder
Elisa Hacker

use of for loop

In [430]:
#reduction
s = 0
for i in range(10):
    s = s + i
print(s)
45
In [431]:
# maaping

sqaures = []
for i in range(10):
    sqaures.append(i*i)
print(sqaures)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [432]:
# filtering

oddsquares = []
for i in range(10):
    if i%2 !=0:
        oddsquares.append(i*i)
print(oddsquares)
[1, 9, 25, 49, 81]

problems

  • Write a python script ls.py which lists contents of current directory.
  • Write a function product which reduces a list by multiplication. Find product of all elements from a list
  • Write a function factorial which computes factorial of a number.
  • Write a function min3 which finds minimum from given three numbers.
In [435]:
%%file ls.py
import sys
import os

def ls(path):
    files = os.listdir(path)
    for f in files:
        print(f)
        
if __name__ == "__main__":
    if len(sys.argv) ==1:
        ls(".")
    else:
        ls(sys.argv[1])
Overwriting ls.py
In [439]:
!python ls.py "/home/vikrant/trainings/"
day5.org~
day5.org
2018
nakul
2017
2019
In [440]:
def product(seq):
    s = 1
    for n in seq:
        s = s*n
    return s
In [441]:
product([1,2,3,4])
Out[441]:
24
In [442]:
def factorial(n):
    return product(range(1,n+1))
In [444]:
factorial(5)
Out[444]:
120
In [445]:
from functools import reduce
In [447]:
def product1(seq):
    return reduce(lambda x,y:x*y, seq, 1)
In [448]:
product1([1,2,3,4,5])
Out[448]:
120
In [449]:
def min3(x,y,z):
    def min2(x,y):
        if x<y:
            return x
        else:
            return y
        
    return min2(min2(x,y),z)
In [450]:
def min2(x,y):
    if x <y:
        return x
    else:
        return y
In [451]:
def min_(seq):
    m = min2(seq[0], seq[1])
    
    for i in seq[2:]:
        m = min2(i, m)
    return m
    
In [453]:
min_([-4,21,3,4,5,6,2,-5])
Out[453]:
-5
In [456]:
def min_(seq, initial=100000000):
    if not seq:
        return None
    
    m = min2(seq[0], initial)
    
    for i in seq[2:]:
        m = min2(i, m)
    return m
    
In [457]:
min_([-4,21,3,4,5,6,2,-5])
Out[457]:
-5
In [460]:
def min_(seq):
    return reduce(min2, seq, 1000000)
In [461]:
min_([-4,21,3,4,5,6,2,-5])
Out[461]:
-5

List comprehensions

In [462]:
squares = []
for i in range(10):
    sqaures.append(i*i)
print(sqaures)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [463]:
[i*i for i in range(10)]
Out[463]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [464]:
[i*i for i in range(20) if i%2==0]
Out[464]:
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
In [465]:
matrix
Out[465]:
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
In [472]:
tables = [[i*j for i in range(1,11)] for j in range(1,6)]
In [469]:
tables
Out[469]:
[[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 [470]:
tables[0] # table for 1
Out[470]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [471]:
tables[1] # table for 2
Out[471]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
In [473]:
tables2 = [[i*j for i in range(1,6)] for j in range(1,11)]
In [474]:
tables2
Out[474]:
[[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]]
In [476]:
tables2[2]
Out[476]:
[3, 6, 9, 12, 15]
In [477]:
tables2[0]
Out[477]:
[1, 2, 3, 4, 5]
In [478]:
tables2[-1]
Out[478]:
[10, 20, 30, 40, 50]
In [482]:
tables[0][4]
Out[482]:
5
In [483]:
tables2[1][4]
Out[483]:
10
In [484]:
tables2[2][4]
Out[484]:
15
In [485]:
def column(data, colnum):
    rowcount = len(data)
    return [data[row][colnum] for row in range(rowcount)]
In [486]:
column(tables2, 4)
Out[486]:
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
In [487]:
column(tables2, 3)
Out[487]:
[4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
In [488]:
matrix
Out[488]:
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
In [489]:
[row for row in matrix]
Out[489]:
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
In [490]:
def transpose(data):
    colcount = len(data[0])
    return [column(data, c) for c in range(colcount)]
In [491]:
transpose(tables2)
Out[491]:
[[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 [493]:
tables2
Out[493]:
[[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]]
In [494]:
zip(names, surnames)
Out[494]:
<zip at 0x7fbb93e95508>
In [496]:
x = [names, surnames]
In [497]:
list(zip(*x))
Out[497]:
[('Elsa', 'Frozen'), ('Alice', 'Wonder'), ('Elisa', 'Hacker')]
In [ ]:
 
In [ ]:
 
In [498]:
list(zip(*tables2))
Out[498]:
[(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 [499]:
tables2
Out[499]:
[[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 which finds all factors of given number
  • write a function is_prime which tell if given number is prime
  • write a function primes to generate prime numbers less than n
In [500]:
def factors(n):
    return [i for i in range(1, n+1) if n%i==0]
In [501]:
factors(10)
Out[501]:
[1, 2, 5, 10]
In [502]:
def is_prime(p):
    return len(factors(p))==2
In [505]:
def primes(n):
    return [p for p in range(2, n) if is_prime(p)]
In [507]:
primes(60)
Out[507]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59]

bonus problems

  • Write a list comprehension to generate 5x5 unit matrix. a unit matrix is a matrix with diagonal element as 1 evry other element is 0
  • Write an expression to sum all multiples of 7 or 11 less than 1000
  • Write a function to rodate 2D list 90 degrees clockwise
  • Write a function to find sum of digits of given integer
    >>> sumdigits(1111)
    4
In [ ]: