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
We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from
2 + 3
There are integers
2 + 3
2 -3
3*3
3 **2
2**100 #power
5/2 #real division
5 // 2 # integer division operator
There are floats
2.3 + 5.5
3.4*3
3.14**2
Text data
"This is text data"
'This is also a string'
s = "Python training going on!"
s
print(s)
print(2)
2
s = "232323"
s
print(s)
sentence = "He said, 'I am fine!'"
print(sentence)
multiline = """one
two
three
"""
print(multiline)
multiline
multi = "Line1\nLine2\n"
windowspath = "c:\\Program Files\\Anaconda"
windowspath
print(windowspath)
star = "*"
star + star
star*5
sentence
sentence[0]
sentence[-1]
sentence[4]
-> 0 1 2 3 4 5
p y t h o n
-6 -5 -4 -3 -2 -1<---
s = "python"
sentence[2]
sentence[5]
sentence[0]
sentence
List ordered items
numbers = [1, 2, 3, 4, 5, 6]
numbers[0]
numbers[-1]
numbers[1]
numbers[2]
matrix = [[1, 1, 1],[2, 2, 2],[3, 3, 3]]
matrix
matrix[0]
matrix[-1]
matrix[0][0]
mixed = ["name", "age", 1, [1, 1, 1]]
mixed
mixed[-1]
mixed[2]
numbers
digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
digits[2:5] # start at index 2 and end at 5 (exluded)
digits[3:7:2] # start at index 3 end at 7 (excluded) at interval of 2
tuples sibling of list
point = (0, 0, 1)
point[0]
point[-1]
point[1:3]
numbers
numbers[0] = 0
numbers
point[0] = -1
sentence[0] = "M"
key value pairs
stock = {"name":"Arcesium", "ticker":"arc", "value":2000}
stock
stock['name']
stock['value']
stock['value'] = 2500
stock
unique unordered values
s = {"one", "two", "two", "three"}
s
yes = True
no = False
None
n = None
n
print(n)
numbers
len(numbers) # length of list
len(sentence) # length of a string
len(s) # length of a set
len(stock) # length of a dictionary
len(point) # length of tuple
n = "32324"
int(n)
float(n)
str(23244343)
problem
2**10002**1000
str(2**1000)
len(str(2**1000))
digits
range(10)
list(range(10))
list(range(1,20,3))
list(range(5)) # end
list(range(3, 10)) # start , end
list(range(2, 15, 3)) # start, end, interval
sum(numbers)
max(numbers)
min(numbers)
max(sentence)
def add(x, y):
s = x + y
return s
add(4,5)
def count_digits(n):
return len(str(n))
count_digits(2**100)
def empty():
pass # a function should have atleast one line it. it can be pass too!
def hello():
problem
twice which just doubles the numbertwice1 to print twice value of a numberthen try
>>> twice(twice(3))
>>> twice1(twice1(3))
def twice(x):
return 2*x
def twice1(x):
print(2*x)
twice(twice(3))
twice1(twice1(3))
twice1(3)
twice(3)
r = twice(3)
r
r1 = twice1(3)
print(r1)
print(2)
x = print(2)
x
print(x)
Every function has to return a value. if not returned explicitly, it returns None
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)
del a
a = 5
def add(x, y):
return x+y
add
aliasadd = add
aliasadd
add(5, 6)
aliasadd(5, 6)
sumofsquare(5,4)
def sumof(f, x, y):
return f(x) + f(y)
sumof(square, 5, 4)
sumof(cube, 5, 6)
max, min, sorted
words = ["one","two","three","four", "five","six"]
max(words)
max(words, key=len)
min(words, key=len)
sorted(words, key=len)
sorted(words)
records = [
("TATA", 200.0, 5.5),
("INFY", 2000.0, -5),
("RELIANCE", 1505.5, 50.0),
("HCL", 1200, 70.5)
]
def get_value(r):
return r[1]
def get_gain(r):
return r[2]
max(records, key=get_value)
max(records, key=get_gain)
sorted(records, key=get_value, reverse=True)
sorted(records, key=get_gain)
def make_logger(logtype):
def logger(msg):
print(logtype + ":", msg)
return logger
info = make_logger("INFO")
error = make_logger("ERROR")
warning = make_logger("WARN")
info
info("Just for your information")
warning("Something is not right, be careful!")
error("Surely things went wrong!")
def make_adder(x):
def adder(y):
return x+y
return adder
adder5 = make_adder(5)
adder5(35)
def make_adder(x):
return lambda y: x+y
adder9 = make_adder(9)
adder9(5)
add = lambda x, y: x+y
add(3,4)
square = lambda x: x*x
square(3)
numbers = [-42,3,5,-3,5]
max(numbers, key=lambda x:x*x)
records
max(records, key=lambda r: r[1])
max(records, key=lambda r:r[2])
text = "Wizard of oz is python 3"
text.upper()
text
text.lower()
text.capitalize()
text.count(" ")
text.replace("python", "scala")
text
text[0] = "A"
text.split()
text.split("is")
text.split() # white spaces, which includes multiple spaces , tabs, newlines
words = text.split()
words
text_trailing = " Wizard of oz is python 3 \n"
print(text_trailing)
text_trailing
text_trailing.split()
words
",".join(words)
text_trailing = ' Wizard,of,oz,is,python,3 '
text_trailing.split(",")
text_trailing.strip().split(",")
text
text.startswith("Wizard")
text.endswith("2.7")
text.center(50)
text.ljust(50)
text.rjust(50)
text.count("i")
numbers
numbers.count(5)
numbers.count(3)
numbers.count(0)
numbers.append(7)
numbers
x = numbers.append(8)
print(x)
numbers
x = numbers.pop()
x
numbers
empty = []
empty.append(0)
empty.append(0)
empty
numbers
numbers.insert(0, -45)
numbers
numbers.sort()
numbers
nums = [-42, 3, 5, -3, 5, 7]
sorted(nums)
nums
numbers
numbers.reverse()
numbers
numbers.extend([1, 2, 3, 4])
numbers
numbers + [1, 2, 3]
t = (1, 1, 1, 0)
t.count(1)
t.index(0)
import os
import math
import math as m
math.pi
m.pi
os.getcwd() # current working directory
os.listdir()
os.listdir("/home/vikrant/trainings/")
problem
countfiles which returns number of files in given directory/folderdef countfiles(path):
return len(os.listdir(path))
countfiles(".")
os.path.exists("/home/vikrant")
os.path.getsize("day1.ipynb")
def biggestfile(path):
files = os.listdir(path)
return max(files, key=os.path.getsize)
biggestfile(".")
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"
text
"python" in text
"scala" not in text
text.endswith("hello")
2 ==3
2 != 3
2 > 3
2 >=3
3 < 5
3 <= 5
stock
"name" in stock ## check in keys of dictionary
"gain" in stock
"value" in stock
numbers
7 in numbers
42 not in numbers
s #set
"one" in s
stock.keys()
stock.values()
"arc" in stock.values()
a = "arc"
b = a
a is b
Various ways to look for help
help(text.lower)
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"
help(filetype)
filetype("hello.py")
%%file mymodule.py
data = 42
def square(x):
return x*x
def say_hello(name):
print("Hello", name)
add location of this module in system variable PYTHONPATH PYTHONPATH=location;
current directory is always in python path
import mymodule
mymodule.data
mymodule.say_hello("Arcesium")
%%file add.py
import sys
def add(x, y):
return x+y
print(sys.argv)
!python add.py 2 3 4 5 6
!python add.py
%%file add1.py
import sys
def add(x, y):
return x+y
add(int(sys.argv[1]), int(sys.argv[2]))
!python add1.py 2 4
%%file add2.py
import sys
def add(x, y):
return x+y
print(add(int(sys.argv[1]), int(sys.argv[2])))
!python add2.py 4 5
Question: How do I take multiple arguments
digits = list(range(10))
digits
digits[2:6]
digits[2:] # drop frist 2
digits[:5] # take first 5
digits[2:7:2]
digits[:] # copy
digits[::-1] # reverse
sum(digits)
sum(['1','2','3'])
list(map(int, ['1','2','3'])) ##apply int function to every item in the list
%%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)
!python add3.py 2 3 4 2 3
from add2 import add
%%file add21.py
import sys
def add(x, y):
return x+y
from add21 import add
%%file add22.py
import sys
def add(x, y):
return x+y
print(__name__)
!python add22.py
import add22
%%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])))
!python add23.py 2 4
from add23 import add
add(5, 6)
def foo(x):
x = 10
a = 12
foo(a)
print(a)
def foo(x):
print("before", x)
x = 10
print("after", x)
a = 12
foo(a)
print(a)
def bar():
print("local", z)
z = 13
bar()
print("global", z)
def bar():
print("local", z)
z = 10
z = 13
bar()
print("global", z)
def bar():
global z
print("before", z)
z = 10
z = 13
bar()
print("global", z)
a, b = 1, 2
a
b
b , a = a, b
def print_fibonaci(n):
curr, prev = 1, 1
while curr < n:
print(curr, end=",")
curr, prev = curr + prev, curr
print_fibonaci(100)
for c in "this sentence":
print(c, end=",")
for num in [1, 2, 3, 4, 5]:
print(num, end=",")
nums
for n in nums:
print(n , n*n)
for s in stock:
print(s, stock[s])
s = set(numbers)
s
for item in s:
print(item, end=",")
for i in range(5):
print(i, end=" ")
sqrs = map(lambda x:x*x, range(1, 11))
sqrs
for i in sqrs:
print(i, end=",")
range(4)
for i in range(5):
print(i, end=",")
list(range(5,0))
l = [1,2,3,4]
#l.reverse() this is one way, but you loose original data
for i in l[::-1]:
print(i, end=",")
for i in reversed(l):
print(i, end=",")
l
lr = reversed(l)
for i in lr:
print(i, end=",")
for i in lr:
print(i, end=",")
words
for w in words:
print(w, end=" ")
for i, w in enumerate(words):
print(i, w)
for i, w in enumerate(words, 100):
print(i, w)
for i, w in enumerate(words):
print(i)
a, b = 1,2
a = 2,3
a
for i in enumerate(words):
print(i)
for i,j,k in enumerate(words):
print(i)
enumerate?
for i in enumerate(words):
print(i)
names = ["Elsa", "Alice", "Elisa"]
surnames = ["Frozen", "Wonder", "Hacker"]
zip(names, surnames)
list(zip(names, surnames))
for n,s in zip(names, surnames):
print(n , s)
names = ["Elsa", "Alice", "Elisa", "Alex"]
surnames = ("Frozen", "Wonder", "Hacker")
for n,s in zip(names, surnames):
print(n,s)
#reduction
s = 0
for i in range(10):
s = s + i
print(s)
# maaping
sqaures = []
for i in range(10):
sqaures.append(i*i)
print(sqaures)
# filtering
oddsquares = []
for i in range(10):
if i%2 !=0:
oddsquares.append(i*i)
print(oddsquares)
problems
ls.py which lists contents of current directory.product which reduces a list by multiplication. Find product of all elements from a listfactorial which computes factorial of a number.min3 which finds minimum from given three numbers.%%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])
!python ls.py "/home/vikrant/trainings/"
def product(seq):
s = 1
for n in seq:
s = s*n
return s
product([1,2,3,4])
def factorial(n):
return product(range(1,n+1))
factorial(5)
from functools import reduce
def product1(seq):
return reduce(lambda x,y:x*y, seq, 1)
product1([1,2,3,4,5])
def min3(x,y,z):
def min2(x,y):
if x<y:
return x
else:
return y
return min2(min2(x,y),z)
def min2(x,y):
if x <y:
return x
else:
return y
def min_(seq):
m = min2(seq[0], seq[1])
for i in seq[2:]:
m = min2(i, m)
return m
min_([-4,21,3,4,5,6,2,-5])
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
min_([-4,21,3,4,5,6,2,-5])
def min_(seq):
return reduce(min2, seq, 1000000)
min_([-4,21,3,4,5,6,2,-5])
squares = []
for i in range(10):
sqaures.append(i*i)
print(sqaures)
[i*i for i in range(10)]
[i*i for i in range(20) if i%2==0]
matrix
tables = [[i*j for i in range(1,11)] for j in range(1,6)]
tables
tables[0] # table for 1
tables[1] # table for 2
tables2 = [[i*j for i in range(1,6)] for j in range(1,11)]
tables2
tables2[2]
tables2[0]
tables2[-1]
tables[0][4]
tables2[1][4]
tables2[2][4]
def column(data, colnum):
rowcount = len(data)
return [data[row][colnum] for row in range(rowcount)]
column(tables2, 4)
column(tables2, 3)
matrix
[row for row in matrix]
def transpose(data):
colcount = len(data[0])
return [column(data, c) for c in range(colcount)]
transpose(tables2)
tables2
zip(names, surnames)
x = [names, surnames]
list(zip(*x))
list(zip(*tables2))
tables2
problems
factors which finds all factors of given numberis_prime which tell if given number is primeprimes to generate prime numbers less than ndef factors(n):
return [i for i in range(1, n+1) if n%i==0]
factors(10)
def is_prime(p):
return len(factors(p))==2
def primes(n):
return [p for p in range(2, n) if is_prime(p)]
primes(60)
bonus problems
>>> sumdigits(1111)
4