Dec 19-21, 2019 Vikrant Patil, Anand Chitipothu
These notes are available online at http://notes.pipal.in/2019/grofers_basic_dec/day1.html
© Pipal Academy LLP
We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from
!pip install jupyter
print("hello world!")
It has integers!
1 + 2
2 - 3
1 / 3 # float divison
5 // 3 # integr division
5 % 2 #mod
5 ** 2 # power
2 ** 1000
It has floats
3.5 * 3.4
there are strings
"Rupali"
'Rupak'
"Rupali" "Rupak"
first = "Rupali"
second = "Rupak"
first
print(first)
first
print(second)
print(first, second)
first
single = 'strign with single quote'
double = "data with double quote"
sentence = "He said, 'Answer to eveything is 42'"
print(sentence)
multiline = """This is multi
line string in python
which has three lines
"""
multiline
print(multiline)
print("string can \t have tabs\n and new lines")
star = "*"
star*5
first + " " + second
print("="*10)
There are lists
numbers = [1, 1, 2, 3, 5, 8, 12]
numeric_data = [1, 1.1, 2.2]
multidata = [1, 2, "a", "b"]
numbers[0]
numbers[-1]
-> 0 1 2 3 4 5
P y t h o n
-6 -5 -4 -3 -2 -1 <--
numbers[2:4] # start at index 2 end at index 4 (exlude)
numbers[:4] #take first 4
numbers[3:] # drop first 3
ones = [1, 1]
ones*5
ones + ones
there are tuple, sibling of list
color = (255, 255, 0)
color[0]
color[-1]
color * 2
color + color
ones
ones[0] = -1
ones
color[-1] = 255
Dictionaries
specs = {"cpu":"core-i5", "memory":16, "os":"mint"}
specs['cpu']
specs['os']
specs['memory']
data = {None:0}
data[None]
specs['memory'] = 8
specs
data[None] = 1
data
del specs['os']
specs
specs['os'] = "linux"
specs
sets
digits = {0, 1, 2, 3, 4}
digits
digits = {0, 0, 1, 1, 2, 3}
digits
digits = {0, 0, 1, 1, 2, 3}
print(digits)
x = 1
y = 2
z = x+ y
print(z**2)
numbers
head, tail = numbers[0], numbers[-1]
print(head, tail)
2,3
x, y = [42, 0]
x, y
head, tail, count = numbers[0], numbers[-1], len(numbers)
head, tail, _ = numbers[0], numbers[-1], len(numbers)
head
del head
head
len(digits)
Boleans are there which talk able truth!
yes = True
arrrr = False
2 > 3
3 >= 5
0 in digits # check if 0 is in set digits
9 in digits
9 not in digits
binary
binary = b'\x064'
print(binary)
binary = b"binary"
binary
numbers
specs
digits
multiline
len(numbers) # length of list
len(specs) # length of dict
len(multiline) # length of string
len(digits) # length of set
str(2**100)
int("355")
float("3.14")
list((255, 0, 0))
tuple([1, 2, 2])
range(10)
list(range(10))
sorted([2, 6, 1, 8, 3, 9, 23])
max([23, 56, 787, 2])
min([23, 45, 7,1])
max(["one", "two", "three"])
sorted(["one", "two", "three"])
sum([1, 2, 3, 4])
2 + "3"
"3" + "2"
result = 2**100
result
len(result)
str(result)
len(str(result))
def add(x, y):
z = x + y
return z
add
add(2, 3)
def compute_powers(x):
sqr = x*x
cube = x*x*x
forth = x**4
return sqr, cube, forth
x_2, x_3, x_4 = compute_powers(2)
print(x_2, x_3, x_4)
def say_hello(person):
print("Hello", person)
say_hello("vikrant")
return_value = say_hello("vikrant")
return_value
print(return_value)
def twice1(x):
print(2*x)
def twice(x):
return 2*x
twice1(2)
twice(2)
twice_twice_5 = twice1(twice1(5))
twice_twice_5 = twice(twice(5))
twice_twice_5
twice1(twice(5))
problems
square to square a numbersumnaturals to find sum of first n natural numberseven to find if given integer is even or not 2 == 3
def square(x):
return x*x
square(5)
def sumnaturals(n):
return sum(range(n+1))
sumnaturals(10)
def even(n):
return n%2 == 0
def odd(n):
return not even(n)
def even(n):
result = n%2
return result == 2
even(3)
sum = 6
sumnaturals(2)
sumnaturals
sum = 6
sum_ = 6
del sum
sumnaturals(5)
def foo(x):
return x**2
foo(5)
foo(5)
help(range)
range?
# above statement will work only inside jupyter/ipython
def sumnaturals(n):
"""
find sum of first n natural numbers
>>> sumnaturals(3)
6
"""
return sum(range(1, n+1))
help(sumnaturals)
def sumofsquares(a, b):
return square(a) + square(b)
def sumofcubes(a, b):
return cube(a) + cube(b)
def cube(x):
return x**3
def sumof(f, x, y):
return f(x) + f(y)
add
sumofsquares(5, 6)
sumof(square, 5, 6)
sumofcubes(5, 6)
sumof(cube, 5, 6)
words = ["one", "two", "three", "four", "five"]
max(words)
max(words, key=len) # parameters can be passed by name
sorted(words)
sorted(words, key=len)
sorted(words, key=len, reverse=True)
max(words, len)
max(words, key=len)
records = [
("Vishakha", 7.8),
("Vishal", 4.5),
("Vaishali", 8),
("Vishwas", 6),
("Vijaya", 5.0)
]
max(records)
sorted(records)
def get_score(r):
return r[1]
max(records, key=get_score)
min(records,key = get_score)
records3 = [
("Vishakha", 7.8, 1),
("Vishal", 4.5, 2),
("Vaishali", 8, 3),
("Vishwas", 6, 4),
("Vijaya", 5.0, 5)
]
def get_roll(r):
return r[2]
def get_name(r):
return r[0]
max(records3, key=get_roll)
max(records3, key=get_name)
sorted_records = sorted(records3, key=get_score)
sorted_records[:2] # top two
sorted(sorted_records, key=get_score)
def make_logger(type_):
def logger(message):
print("[" + type_.upper() + "]:", message)
return logger
warn = make_logger("warning")
error = make_logger("error")
info = make_logger("info")
critical = make_logger("critical")
warn
warn("This is warning message ..be careful")
error("Some thing wrong...Error")
info("just for your information")
critical("You are doomed!")
def make_adder(x):
def adder(y):
return x+y
return adder
adder5 = make_adder(5)
adder5(10)
adder7 = make_adder(7)
adder7(10)
There is a handy way of writing a function on fly
max(records, key=lambda r: r[1])
sqr = lambda x: x*x
sqr(4)
def make_adder(x):
return lambda y: x+y
text = "This a text from some novel"
text.lower()
text[0]
text[0] = t
text.lower()
text
text.upper()
text.count("o")
text.index("e")
text.split()
commaseperated = "Helo,this,is,another,text"
commaseperated.split(",")
multiline
multiline.split()
text.split(" ")
text.split()
multiline.split(" ")
multiline.split("\n")
trailing = " hello there..... I am just adding few trailing \n"
trailing.strip()
def get_words(textdata):
return textdata.strip().split()
get_words(multiline)
text.startswith("T")
text.endswith("py")
"this" in text
"this" in text.lower()
text.center(50)
text.rjust(50)
text.ljust(50)
"this".lower() == "This".lower()
text.split()
words = text.split()
words
"_".join(words)
" ".join(words)
"/".join(["","home","vikrant","trainings"])
numbers
numbers.count(1)
numbers.append(23)
numbers
numbers.pop()
numbers
numbers.insert(0, 0)
numbers.remove(0) #removes item
empty = []
empty.append(1)
empty.append(1)
print(empty)
randomnums = [3, 6, 2, 1, 87, 2]
randomnums.sort() # sorts list in place
randomnums
sorted(numbers)
sorted(randomnums, reverse=True) # does not change original list
randomnums
t = (1, 0, 1)
t.index(0)
t.count(1)
nums_copy = numbers.copy()
nums_copy
problems
count_zeros which counts number of zeros from 2**100names = ["anand", "Boby", "chitra", "David"]
>>> rearrangemax(4367)
7643
2**100
ord("a")
ord("A")
def count_zeros(n):
return str(n).count("0")
count_zeros(2**100)
count_zeros(2**1000)
names = ["anand", "Boby", "chitra", "David"]
def ignorecase(text):
return text.lower()
max(names, key=ignorecase)
def rearrangemax(n):
digits = list(str(n))
return int("".join(sorted(digits, reverse=True)))
rearrangemax(45378)
list("3443")
import math # this import math module
math.pi
from math import pi # only imports pi
pi
import math as m
import numpy as np
import pandas as pd
m.sin(pi/4)
math.sin(pi/4)
import time
time.time()
time.asctime()
%%file date.py
import time
def print_date():
print(time.asctime())
#print_date()
import date
date.print_date()
!python date.py
%%file date1.py
import time
def print_date():
print(time.asctime())
print_date()
!python date1.py
import date1
__name__¶%%file magic.py
print(__name__)
!python magic.py
import magic
%%file today.py
import time
def print_date():
print(time.asctime())
if __name__ == "__main__":
print_date()
import today
!python today.py
2 > 3
2 == 2
first == "Rupali"
specs
"os" in specs
names
"anand" in names
text
"novel" in text
"today.py".endswith("py")
cond1 = 2>3
cond2 = "hel" in "hello"
cond1 or cond2
cond1 and cond
not cond1
def check_file_type(filename):
if filename.endswith(".py"):
return "python"
elif filename.endswith(".exe"):
return "executable"
elif filename.endswith(".txt"):
return "text"
else:
return "Unknown"
check_file_type("hello.py")
def min2(x, y):
if x < y:
return x
else:
return y
min2(5, 45)
min2(45, 5)
problems
min3 which find minimum number from gvien three numbers>>> min3(6,2,8)
2
min4 which ffinds minimum from given four numbers>>> min4(8, 2, 5, 7)
2
def min3(x, y, z):
return min2(min2(x, y), z)
def min4(p, q, r, s):
return min2(min3(p, q, r), s)
%%file minimum.py
def min2(x, y):
"""
>>> min2(2, 3)
2
>>> min2(3, 2)
2
>>> min2(2, 2)
2
"""
if x < y:
return x
else:
return y
def min3(x, y, z):
"""
>>> min3(1, 2, 3)
1
>>> min3(2, 1, 3)
1
>>> min3(2,3,1)
1
"""
return min2(min2(x, y), z)
def min4(p, q, r, s):
"""
>>> min4(1, 1, 2, 3)
2
"""
return min2(min3(p, q, r), s)
!python -m doctest -v minimum.py
!pip install pytest
%%file test_min.py
import minimum
def test_min2():
assert minimum.min2(1, 2)==1
assert minimum.min2(1,1)==1
assert minimum.min2(2,1)==1
def test_min3():
assert minimum.min3(1, 2, 3)==1
assert minimum.min3(1,1, 1)==1
assert minimum.min3(2,1, -1)==1
!pytest test_min.py
!pytest
import random
nums = ["one", "two", "three", "four", "five", "six"]
random.choice(nums)
random.choice(nums)
random.choice(nums)
random.choice(nums)
random.choices(nums, k=2)
random.random()
help(max)
import sys
%%file square.py
import sys
def square(x):
return x*x
if __name__ == "__main__":
print(sys.argv)
n = int(sys.argv[1])
print(square(n))
!python square.py 2
!python square.py 2 2 3 4 5
%%file square1.py
import sys
def square(x):
return x*x
if __name__ == "__main__":
n = int(sys.argv[1])
print(square(n))
!python square1.py 6
def print_fib(n):
prev, cur = 1, 1
while cur < n:
prev, cur = cur, prev+cur
print(prev, end=",")
print_fib(100)
for num in numbers:
print(num, end=" ")
for c in "This is some text to go through!":
print(c, end=" ")
for item in specs:
print(item)
for item in (1, 1, 1, 2, 3, 4):
print(item, end=" ")
charset = set("this is some text to be used for testing set...how many char?")
for c in charset:
print(c, end=",")
def sumlist(numbers):
s = 0
for num in numbers:
s += num
return s
sumlist([1,2,3,4,5,6])
fibnums = [1,2,3,5,8,13,21,34,55,89]
len(fibnums)
fibnums[3:7] # starts at index 3 ends at index 6
fibnums[2:9:2] # start at index 2 end at index 8 at interval of 2
fibnums[:] # copy
fibnums[::2] # take alternate items
fibnums[::-1] #reverse
fibnums[:2] # take first two
fibnums[3:] # drop first 3
fibnums[:-2] #drop last two
problems
python mysum.py 1 2 3 4
10
python mysum.py 2 3
5
args = ["mysum.py", "1", "2", "3", "4"]
args[1:]
%%file mysum.py
import sys
def mysum(items):
s = 0
for item in items:
s += int(item)
return s
if __name__ == "__main__":
print(mysum(sys.argv[1:]))
!python mysum.py 1 2 3 4 5
x = [1, 1, 0]
y = x
y.append(-1)
print(x)
x = [1, 1, 1]
y = x
y = [0, 0, 0]
print(x)
def append_one(nums):
nums.append(1)
x = [0, 0, 0]
append_one(x)
print(x)
def foo(nums):
nums = [1,2,3]
x = [0, 0, 0]
foo(x)
print(x)
def bar(x):
return x+y
del x,y
bar(4)
y = 10
bar(5)
def foobar(x):
global y
y = 15
return x+y
foobar(4)
y