Jun 03-04, 2019 Vikrant Patil
These notes are available online at http://notes.pipal.in/2019/arcesium_basic_jun/day1.html
© Pipal Academy LLP
We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from
2 + 4
2 ** 100
there are integers
2 + 2
2 - 3
2 / 3
3 // 2
2 * 3
2 **100
5 % 2
there are floats
2.5
3/5
3 + 5.0
3.0 ** 5
3.0 ** 4.5
there are strings
"This is a text data"
"Hello" + " World!"
"*"*5
"hello"*5
text = "This is some random text"
text[0]
text[2]
text[-1]
Indexing strings
->0 1 2 3 4 5
p y t h o n
-6 -5 -4 -3 -2 -1 <-
multiline = """ line 1
line2
line3
line4
"""
print(multiline)
print(text)
import this
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!
"""
print(poem)
multi= "line1\nline2\nline3"
multi1 = """line1
line2
line3"""
print(multi)
print(multi1)
"he said, 'I am fine'"
"hello\""
'hello"'
There are lists
emptylist = []
numbers = [1, 2, 3, 4, 5, 6]
print(numbers)
numbers[0]
numbers[-1]
ones = [1, 1, 1, 1]
ones + ones
ones
ones*4
mixed = [1, 2, "data1", "python", 2.5]
mixed[-1]
mixed
mixed = [ones, numbers, 1, 2, 3, 4]
mixed
ones.append(0)
ones
mixed
there are tuples, sibling of list
t = (1, 2, 3, 4)
t[0]
t[-1]
t+ t
t*3
ones[-1] = 1
ones
t[-1] = 0
name = "python"
name[0] = "P"
name[0]
there is binary
binary = b"this i sstring strored as binary"
binary
"hello" + binary
binary = b"\x22\x67\x65"
binary
print(binary)
there are dictionaries
company = {"name":"Arcesium", "location":"Hyderabad"}
company['name']
company["location"]
company['ticker']
company['ticker'] = "ARC"
company['ticker']
company
there are sets
chars = {"A","B","C","C","C"}
chars
{"A":"a", "B","C"}
boolean
yes = True
no = False
nothing
nothing = None
""
[]
()
{}
pass
key1= "processor"
key2 = "os"
key3 = "memory"
specs = {key1:"Corei5", key2:"mint", key3:"4GB"}
specs
key3 = "RAM"
specs
data = {1:"One", 2:"Two"}
data
data[1]
data[-1]
d = {1:[1, 1, 1, 1], 2:[2, 2, 2, 2]}
d[1]
d[2]
d = {"One":[1, 1, 1, 1], "Two":[2, 2, 2, 2]}
d = {(1, 1):"one", (2, 2):"two"}
d = {[1, 1]:"one", [2, 2]:"two"}
specs['memory'] = "8GB"
specs
specs["brand"] = "Acer"
specs
table = [specs]*10
table[4]['processor'] ## 4th row->dict->processor
len("this string")
len(specs)
len(table)
len((1, 1, 1,1, 1))
specs
int("45")
float("3.0")
str(3.0)
r = range(10)
list(r)
list(range(1,10))
list(range(1,20,3))
sum(ones)
problems
2**1000sum(range(1, 101))
n = 2**1000
len(n)
len(str(n))
len(str(3.45))
def hello():
print("Hello there!")
print("Another Hello!")
print("Task done!...exiting")
hello()
def hello():
print("Hello there!")
print("Another Hello!")
print("Task done!...exiting")
hello()
def count_digits(n):
return len(str(n))
count_digits(2**100)
count_digits(2**1000)
n
def add(x, y):
return x+y
add(3, 5)
x = 10
y = 45
add(5, 6)
x
y
def twice(x):
y = x
return 2*x
twice(5)
y
g = 10
def accessgloabal():
print(g)
accessgloabal()
def twice1(x):
print(2*x)
twice1(5)
twice(5)
a = add(3, 5)
t6 = twice(6)
t6
t7 = twice1(7)
print(t7)
A function with no return statement by default returns None
twice(twice(5))
twice1(twice1(5))
def sumofsquares(x, y):
return square(x) + square(y)
sumofsquares(5, 6)
def square(a):
return a*a
square
square(4)
sumofsquares(5, 6)
fun = square
x = 5
y = x
square
fun = square
fun
fun(5)
def square(a):
return a*a
def cube(x):
return x*x*x
def zeta(x):
return None
def sumofsquares(x, y):
return square(x) + square(y)
def sumofcubes(a, b):
return cube(a) + cube(b)
def sumof(func, x, y):
return func(x) + func(y)
sumof(square, 2, 3)
sumof(cube, 3, 4)
int("2")
float("3.0")
str(2324)
sum([1, 2, 3, 45])
max([1, 2, 3, 45])
min([-1, 2, 3, 4, 565])
words = ["one", "two", "three", "four", "five"]
max(words)
max(words, key=len)
help(max)
max(words, len)
max(words, key=len)
2
3
4
print(2)
print(3)
print(4)
text = "hello"
text
print(text)
square
print(square)
# (ticker, value, gain)
stocks = [("HCL", 500.0, 10.0),
("INFY", 800.0, 8.0),
("TATA", 247, 3),
("MM", 530, -5)]
stocks = [("HCL", 500.0, 10.0), ("INFY", 800.0, 8.0), ("TATA", 247, 3),("MM", 530, -5)]
max(stocks)
def getvalue(r):
return r[1]
def getgain(r):
return r[2]
max(stocks, key=getvalue)
max(stocks, key=getgain)
min(stocks, key=getgain)
def make_logger(type_):
def logger(message):
print("[" + type_ + "]:", message)
return logger
info = make_logger("INFO")
print(info)
warning = make_logger("WARN")
error = make_logger("ERROR")
info("Just for information")
warning("Something might go wrong!")
error("Boom! Something went wrong")
def make_adder(x):
def adder(y):
return x+y
return adder
adder5 = make_adder(5)
adder5(5)
adder5(100)
def foo():
pass
f = lambda x,y: x+y
f(3,4)
max(stocks, key=lambda r: r[1])
sorted([3, 4, 5,6,1 ,4])
sorted(stocks, key=getvalue, reverse=True)
stocks[1]
stocks
stocks[1]
def column(colnum):
return lambda r: r[colnum]
max(stocks, key= column(1))
max(stocks, key= column(2))
statement = "Wizard of oz is python!"
statement.upper()
statement.split() # without parameter is white space (any and any numner of)
words = statement.split()
words
",".join(words)
",".join(words).split(",")
statement.replace("python", "Haskell")
statement.startswith("Wizard")
statement.split('o')
statement.lower().split("o")
" with some trainling spaces \n".strip()
statement.endswith("sdasd")
statement.center(50)
print(poem)
statement.ljust(50)
statement.rjust(50)
help(str)
digits = list(range(10))
digits
digits.append(-1)
digits
digits.pop() # remove last element
digits.insert(0, -1) # insert element at position zero
digits
digits.pop(0) # it pops 0th element
digits
digits.reverse()
digits
digits.extend([1,1,1,1,1])
digits
digits.remove(5) # remove element '5'
digits
digits.index(4)
digits.index(9)
digits.index(5)
digits.sort()
digits
digits.count(5)
digits.count(1)
1 == 1
1 != 2
statement
statement.startswith("W")
statement.endswith("!")
"python" in statement
5 in digits
specs
"os" in specs
"brand" in specs
"Corei5" in specs.values()
3 in 5
"3" in "3333333"
def filetype(filename):
ext = filename.split(".")[-1]
if ext == "py":
return "python"
elif ext == "exe":
return "executable"
elif ext == "hs":
return "haskell"
else:
return "Unknown"
filetype("hello.py")
def filetype(filename):
if filename.endswith("py"):
return "python"
elif filename.endswith("exe"):
return "executable"
elif filename.endswith("hs"):
return "haskell"
else:
return "Unknown"
filetype("windows.exe")
problems
>>> min2(4,5)
4
>>> min3(3,4,1)
1
def min2(x,y):
if x < y:
return x
else:
return y
def min3(x, y, z):
return min2(min2(x, y), z)
import math
import os
math
math.pi
from math import sqrt
sqrt(4)
from math import sqrt as suareroot
import time
time.time()
def timeit(f):
start = time.time()
f()
end = time.time()
return end - start
def distance(x1, y1, x2, y2):
return math.sqrt((x2-x1)**2 + (y2-y1)**2)
def distance2(x1, y1, x2, y2):
return sqrt((x2-x1)**2 + (y2-y1)**2)
def testfunc1():
for i in range(10000000):
distance(5,4,6,2)
def testfunc2():
for i in range(10000000):
distance2(5,4,6,2)
timeit(testfunc1)
timeit(testfunc2)
def foo1(a, b, c):
print(a, b, c)
def foo2(a, b, c=0):
print(a, b, c)
foo1(1, 2, 3)
foo2(1, 2)
foo2(1, 2, 4)
foo1(a=3, c=2, b =1)
args = (1, 2, 3)
foo1(*args)
foo1(args)
kwargs = {"a":1, "b":2, "c":3}
foo1(**kwargs)
kwargs = {"a":1, "b":2, "c":3, "d":5}
foo1(**kwargs)
import math
import math as m
from math import sqrt
from math import sqrt as squareroot
import pandas as pd
os.getcwd()
import os
cwd = os.getcwd()
os.listdir(cwd)
os.getlogin()
os.getenv("PYTHONPATH")
os.path.sep
os.path.sep.join(["","home", "vikrant", "trainings"])
os.path.getsize("day1.html")
max(os.listdir(cwd), key= os.path.getsize)
os.path.exists("hello.py")
os.path.exists("day1.ipynb")
%%file hello.py
def say_hello(name):
print("Hello", name)
import hello
hello.say_hello("Python")
!python hello.py
%%file hello1.py
def say_hello(name):
print("Hello", name)
print("Hello!")
!python hello1.py
%%file hello2.py
import sys
def say_hello(name):
print("Hello", name)
print(sys.argv)
say_hello(sys.argv[1])
!python hello2.py python kjsahd kjsahd askjh dskfh sd kdsjhfkasdj
%%file square.py
import sys
def square(x):
return x*x
n = float(sys.argv[1])
print(square(n))
!python square.py 5
import square
from square import square
fun
__name__
%%file square1.py
import sys
def square(x):
return x*x
print(__name__)
if __name__ == "__main__":
n = float(sys.argv[1])
print(square(n))
!python square1.py 67
import square1
square1.square(45)
%%file square2.py
import sys
def square(x):
return x*x
def modulename():
print(__name__)
if __name__ == "__main__":
n = float(sys.argv[1])
print(square(n))
import square2
square2.modulename()
__name__
square2.__name__
numbers = [1, 2, 3, 5, 8, 13, 21, 34, 55]
numbers[0]
numbers[2:5] ## items from 2nd index till 5th index (excluded)
numbers[:5] # from start till 5th index (exluded)
numbers[3:] # start from 3rd index till end
numbers[:3] # take first 3
numbers[2:] # drop first two
numbers[1:8:2] # start at index 1 end at index 7 at distance of 2
numbers[:] # copy
numbers[3:-1] # drop 3 from front drop 1 from tail
numbers[::-1] # reverse
def is_palindrome(word):
return word == word[::-1]
is_palindrome("madam")
len(numbers)
numbers[3:100]
numbers[100]
numbers[300:]
"hello world"[::-1]
x, y = 2, 3
x = 5
y = 10
y, x = x, y
x
y
prev = 1
curr = 1
while curr < 100:
prev, curr = curr, prev+curr
print(curr, end=",")
def print_fibionacci(n):
prev = 1
curr = 1
while curr < n:
prev, curr = curr, prev+curr
print(curr)
print_fibionacci(100)
def print_fibionacci(n):
prev = 1
curr = 1
while curr < n:
prev, curr = curr, prev+curr
print(curr, end=" ")
print_fibionacci(100)
def print_fibonacci(n):
"""
prints all fibonacci numbers less than n
"""
prev = 1
curr = 1
while curr < n:
prev, curr = curr, prev+curr
print(curr, end=" ")
help(print_fibonacci)
numbers
for fib in numbers:
print(fib, end=",")
for w in words:
print(w)
for c in statement:
print(c, end=",")
for item in specs:
print(item, specs[item])
for key, value in specs.items():
print(key, value)
for fib in numbers[:5]:
print(fib, end=",")
!ls
%%file ls.py
import os
def ls(location=None):
if location==None:
location = os.getcwd()
files = os.listdir(location)
for f in files:
print(f)
if __name__ == "__main__":
ls()
!python ls.py
problems
sum(numbers)
sum(words)
def mysum(items):
s = 0
for item in items:
s += item
return s
def product(items):
p = 1
for item in items:
p *= item
return p
def factorial(n):
return product(range(1, n+1))
isinstance(2, int)
def mysum(items):
if items and isinstance(items[0], str):
s = ""
else:
s = 0
for item in items:
s += item
return s
mysum(words)
mysum(numbers)
from functools import reduce
help(reduce)
reduce(lambda x, y: x+y , numbers)
reduce(lambda x, y: x*y , range(1, 5))
import operator
operator.add
for i in numbers:
print(i*i, end=",")
def squares(seq):
s = []
for item in seq:
s.append(item**2)
return s
[item**2 for item in numbers]
squares(numbers)
def squares(numbers):
return [item**2 for item in numbers]
def evens(numbers):
s = []
for i in numbers:
if i%2==0:
s.append(i)
return s
evens(numbers)
[i for i in numbers if i%2==0]
def listpy(location):
files = os.listdir(location)
return [f for f in files if f.endswith(".py")]
listpy(os.getcwd())
problems
factors using list comprehension which finds all factors of given number.is_prime which tells whether given number is prime or notprimes which generates all primes less than n[i for i in range(5)]
[[i+j for i in range(5)] for j in range(5)]