Apr 15-18, 2019 Vikrant Patil
These notes are available online at http://notes.pipal.in/2019/arcesium_basic_apr/day2.html
© Pipal Academy LLP
We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from
text = "Some text with some words in it"
text.startswith("S")
text.lower()
text.upper()
text.split()
words = text.split()
words
"-".join(words)
"_".join(words).split()
"_".join(words).split("_")
words
words.append("One")
words
words.pop(0)
words
words.insert(0, "Some")
words
words.extend(["two", "three", "four"])
words
words.pop()
words
words.pop(-1)
problem
count_zeros count zeros in given integer.>>> count_zeros(1000)
3
max(text)
numbers= [1, 2, 3,4 , 5]
t = (1, 2, 3, 4, 5)
numbers[0] = 0
numbers
t[0] = 0
t[0]
def foo(x):
return x*x+1
foo(5)
foo(3)
def count_zeros(n):
return str(n).count("0")
count_zeros(1000**100)
list(range(1, 30, 5))
list(range(10))
list(range(1,10))
words
words = "Wizard of oz is python programmer".split()
words
words[0]
words[-1]
words[2:5]
words[1:5:2]
digits = list(range(10))
digits
digits[1:8:2]
digits[:] # copy of digits
x = [1,1,1,1]
y = x
x.append(0)
x
y
y.pop()
y
x
z = x[:] # new copy
z
x.append(0)
x
z
digits[2:] #drop frist two
digits[:5] #take first 5
digits[:-1]
digits[::-1] ## reverser the list
splicing also works for strings
text[:10]
text[::-1]
digits[2:7] # start at index 2 till index 6 (excludes 7)
digits[2:] # starts at index 2 ..till end
digits[:5] # starts at index 0 till index 4 (excluded 5)
numbers = list(range(1, 10))
numbers
numbers[:4]
numbers[3]
def head(seq, n):
return seq[:n]
head(words, 3)
head
When to use round bracket and when to use square bracket?
When you want to call a function you use round bracket.
when you want to access element from a list, string, tuple, dictionary you should use square bracket
seq
def func(x):
return x*x
x = 5
func(7)
func(x)
import math
math
def cyl_volume(radius, height):
area = math.pi*radius**2
return area*height
cyl_volume(1, 10)
math.sin(math.pi)
help(math.ceil)
math.ceil(4.3)
math.ceil(4.9)
from math import ceil
ceil(30.4)
help(sorted)
def sumofsquares(x,y):
def square(a):
return a*a
return square(x) + square(y)
Just like there can be function inside function. There can be module in inside module.
from os import path
path.exists("c:")
help(math)
import os
os.getcwd() # get current working directory
os.listdir()
os.listdir("/home/vikrant/") # windows users can give c:
def countfiles(directory):
contents = os.listdir(directory)
return len(contents)
cwd = os.getcwd()
countfiles(cwd)
os.path.exits("hello.txt") # relative path, looked into current directory
os.path.exists("/home/vikrant/trainings") # absolute path. for windows it starts with drive name
cwd
os.path.sep
cwd = os.getcwd()
filename = "hello.txt"
cwd + "/" + filename
filepath = os.path.sep.join([cwd, filename])
filepath
os.path.exists(filepath)
os.path.exists(os.path.join(cwd, "day1.html"))
os.path.getsize("day1.html")
def biggestfile(directory):
files = os.listdir(directory)
return max(files, key=os.path.getsize)
biggestfile(os.getcwd())
files = os.listdir(cwd)
files
max(files)
max(files, key=len)
max(files, key=os.path.getsize)
Question
We dot while calling methods from objects like string, list, dictionary, set...
while calling functions from modules or accessing variable data from module.
math.pi
os.path.sep
"_".join(["hello", "world"])
join()
def mysum(x, y, z):
return x+y+z
mysum(1, 2, 4)
mysum(1, 2, 3,4, 5, 6, 7)
def mysum1(numbers):
return sum(numbers)
mysum1([1,2,34,45,12,3,5])
%%file mymath.py
mypy = 22.0/7
def square(x):
return x*x
def sqrt(x):
return x**0.5
os.listdir()
os.path.exists("mymath.py")
import mymath
mymath.mypy
mymath.sqrt(2)
from mymath import sqrt
sqrt(5)
%%file mymath1.py
mypy = 22.0/7
def square(x):
return x*x
def sqrt(x):
return x**0.5
print(sqrt(5))
!python mymath1.py
To make your program reusable it is necessary to pass some inputs to your script. Those inputs should be used by the pythom script. We will pass inputs using command line arguments.
%%file mymath2.py
import sys
mypy = 22.0/7
def square(x):
return x*x
def sqrt(x):
return x**0.5
print("Arguments ->", sys.argv)
z = float(sys.argv[1])
print(sqrt(z))
!python mymath2.py 5 argg1 arg2 arg3 arg4 jlkdsjf sdlfkjsdlkfjs sdlkfjsd
!python mymath2.py
import mymath2
from mymath2 import sqrt
def foo():
print("foo")
foo()
def hello():
print("hello")
def hello():
print("foo")
hello()
%%file mymath3.py
import sys
mypy = 22.0/7
def square(x):
return x*x
def sqrt(x):
return x**0.5
def main():
print("Arguments ->", sys.argv)
z = float(sys.argv[1])
print(sqrt(z))
from mymath3 import sqrt
"hello.py".endswith(".py")
words
"python" in words
"java" not in words
stock = {"name":"HCL", "value":500, "exchange":"BSE"}
"name" in stock # check if name exists in keys
"gain" in stock
x = 2
x == 2
x != 3
x > 5
x <= 4
x >= 0
"hello" == "hello"
"hello" == "HELLO".lower()
stock.keys()
stock.values()
"BSE" in stock.values() # check if BSE exists in values
if "name" in stock:
print(stock['name'], stock['value'])
if "name" in stock and "value" in stock:
print(stock['name'], stock['value'])
if "name" in stock and "gain" in stock:
print(stock['name'], stock['gain'])
else:
print("Data is not there!")
languanges = ["python3", "java", "c", "english"]
if "python" in languanges:
print("python there!")
elif "french" in languanges:
print("frennch is there")
elif "telugu" in languanges:
print("telugu is there")
else:
print("No comman langauage found!")
%%file mymath4.py
import sys
mypy = 22.0/7
def square(x):
return x*x
def sqrt(x):
return x**0.5
def main():
print("Arguments ->", sys.argv)
z = float(sys.argv[1])
print(sqrt(z))
print(__name__)
!python mymath4.py
import mymath4
%%file mymath5.py
import sys
mypy = 22.0/7
def square(x):
return x*x
def sqrt(x):
return x**0.5
def main():
print("Arguments ->", sys.argv)
z = float(sys.argv[1])
print(sqrt(z))
print("__name__ =", __name__)
if __name__ == "__main__":
main()
!python mymath5.py 8
from mymath5 import sqrt
foobar()
def foobar():
print("foobar")
%%file mymath6.py
import sys
mypy = 22.0/7
def square(x):
return x*x
def sqrt(x):
return x**0.5
def main():
print("Arguments ->", sys.argv)
z = float(sys.argv[1])
print(sqrt(z))
print("__name__ =", __name__)
if __name__ == "__main__":
main()
!python mymath6.py 7
import mymath6
problem
add.py which will add two number given from command line.
python add.py 5 6
11
palindrom.py which will can tell if given word/number is palindrom or not.
python palindrom.py madam
True
python palindrom.py hello
False
rearrangemax.py which will rearrage digits of a number to from maximum number
python rearrangemax.py 4236
6432
%%file add.py
import sys
def main():
print(float(sys.argv[1]) + float(sys.argv[2]))
if __name__ == "__main__":
main()
!python add.py 54 4
%%file add1.py
import sys
print(float(sys.argv[1]) + float(sys.argv[2]))
!python add1.py 4 5
import add1
list(map(float, ["1", "2", "3"]))
def square(x):
return x*x
list(map(square, [1, 2, 3, 4]))
%%file addmany.py
import sys
def main():
values = sys.argv[1:]
numbers = map(float, values)
print(sum(numbers))
if __name__ == "__main__":
main()
!python addmany.py 2 3 4 1 12.4 5
!python addmany.py 2 3 4 1
%%file palindrom.py
import sys
def is_palindrom(word):
return word == word[::-1]
if __name__ == "__main__":
print(is_palindrom(sys.argv[1]))
!python palindrom.py madam
!python palindrom.py 1221
!python palindrom.py 12211
s = "7787340"
sorted(s, reverse=True)
list(s)
%%file rearrangemax.py
import sys
def rearrangemax(n):
s = str(n)
return int(rearrange_s(s))
def rearrange_s(value):
digits = sorted(value, reverse=True)
return "".join(digits)
if __name__ == "__main__":
print(rearrange_s(sys.argv[1]))
!python rearrangemax.py 6345
from rearrangemax import rearrangemax
rearrangemax(45677)
del rearrangemax
def rearrangemax(n):
s = str(n)
return int(rearrange_s(s))
rearrangemax(34343)
def rearrange_s(value):
digits = sorted(value, reverse=True)
return "".join(digits)
rearrangemax(3432)
del rearrangemax
def rearrangemax(n):
s = str(n)
return int(rearrange_s(s))
def rearrange_s(value):
digits = sorted(value, reverse=True)
return "".join(digits)
rearrangemax(45454)
import time
n = 10
while n>0:
print("Tick-" + str(n))
time.sleep(1)
n = n - 1
print("Boooom!!!!")
n = 10
while n>0:
print("Tick-" + str(n))
time.sleep(1800)
n = n - 1
print("Boooom!!!!")
print("hello")
problem
print_evens which prints first n even numbers.
>>> print_evens(5)
0
2
4
6
8
n = 10
i = 0
while i<n:
print(i)
i = i+1
def even(x):
return x%2==0
even(5)
even(4)
n = 10
i = 0
count = 0
while count<n:
if even(i):
print(i)
count = count+1
i = i+1
def print_evens(n):
nums = list(range(0, 2*n, 2))
nums.reverse()
while nums:
print(nums.pop())
print_evens(5)
def print_evens(n):
nums = list(range(0, 2*n, 2))
while nums:
print(nums.pop(0))
print_evens(6)
def empty(x):
if x:
print("Non empty")
else:
print("Empty")
empty("")
empty({})
empty([])
x, y , z = 1, 2, 3 # multiple assignments in single statement
x
y
z
x, y = [4,5]
x
x, y = x+y, 5
x
y
list(map(int, ["2","3","5"]))
words
for w in words:
print(w.rjust(10))
for word in words:
print(word.rjust(10))
for n in range(5):
print(n)
for n in range(5):
print(n, end=" ")
words
for w in words:
print(w, end=" ")
def mysum(seq):
s = 0
for item in seq:
s = s + item
return s
mysum([1, 2, 3, 4, 5])
mysum(words)
def mysum(seq, initial=0):
s = initial
for item in seq:
s = s + item
return s
mysum([1,2,3,4,5])
mysum(words, "")
def product(numbers):
p = 1
for n in numbers:
p = p*n
return p
product([1,2,3,4,5])
def factorial(n):
return product(range(1, n+1))
factorial(3)
factorial(5)
def square(numbers):
s = []
for n in numbers:
s.append(n*n)
return s
square(range(5))
def toint(seq):
i = []
for item in seq:
i.append(int(item))
return i
toint(["1","34","5"])
def odds(seq):
o = []
for item in seq:
if not even(item):
o.append(item)
return o
odds(range(20))
python 2 syntax
print "hello"
python 3 syntax
print("hello")