Dec 13-15, 2017 Vikrant Patil
These notes are available online at http://notes.pipal.in/2017/vmware-nov-python
© Pipal Academy LLP
2 + 3
print("hello")
name = "Python"
name
print(name)
2 + 3
2 - 4
3 ** 2
2 ** 1000
3 / 2
3 // 2
2.0 + 1
name = "Rupali"
second = "Rupak"
name + " " + second
star = "*"
star*5
singlequoted = 'string with " quote inside'
print(singlequoted)
doublequoted = "string with ' quote inside"
multiline = """
this is a multi
line
string
with 4 lines
"""
print(multiline)
multiline
tabed = "rupali\trupak"
print(tabed)
regional = "आ ष"
regional
unicode = "\uc085"
print(unicode)
binary = b'hello python'
print(binary)
binary.decode()
"string".encode()
ones = [1,1,1,1]
ones[0]
digits = [1,2,3,4,5,6,7,8,9]
digits[0]
digits[2]
digits[-1]
digits[-5]
digits[:2] # everything till second index
digits[2:] # drop first two
ones
moreones = ones * 5
moreones
len(ones)
tuples
tigits = (1,2,3,4,5,6,7,8,9)
tigits*2
tigits[0]
tigits[-1]
tigits[1:]
sentence = """
some random statement
just to check how many english alphabets
are used in it
"""
s = set(sentence)
s
person = {"name":"alice", "email":"alice@wonder.land"}
person['name']
len("this is a string to test len")
len(ones)
len(tigits)
len(s)
len(person)
str(121232)
int("45")
problem find number of digits in 2**100
value = 2**100
value
strvalue = str(value)
strvalue
len(strvalue)
s = "some string so that you understand \n new line"
s
print(s)
repr(s)
total = "first" "second"
total
Will this work?
pre = "Isac"
post = "Asimove"
name = pre post
2 + "3"
len([1,2,3,4])
def square(x):
return x*x
def say_hello(name):
print("hello", name)
square(2)
say_hello("python")
sqr2 = square(2)
sqr2
value = say_hello("Python")
print(value)
value
value = None
def twice(x):
return 2*x
def twice1(x):
print(2*x)
twice(twice(twice(2)))
twice1(twice1(2))
def count_digits(n):
return len(str(n))
count_digits(2**1000)
def add(x, y):
return x+y
add
print(add)
aliasadd = add
aliasadd
add(2,4)
aliasadd(2,4)
def square(x):
return x*x
def sumofsquares(x,y):
return square(x) + square(y)
def cube(x):
return x**3
def sumofcubes(x,y):
return cube(x) + cube(y)
def sumof(func, x, y):
return func(x) + func(y)
sumofsquares(2,3)
sumof(square, 2, 3)
sumofcubes(2,3)
sumof(cube, 2, 3)
def fourthpower(x):
return x**4
sumof(fourthpower, 3, 4)
Functions are just like any other object. You can pass functions as argument just like any other variables, you can return functions just like a variable.
squares = lambda x: x*x
square(2)
sumof(lambda y:y**4, 3,4)
diff = lambda x,y : y-x
diff(5,7)
def make_adder(x):
def adder(y):
return x+y
return adder
adder5 = make_adder(5)
adder5
adder5(4)
adder5(5)
adder5(6)
Passing functions as parameter to function makes that function usable in multiple conditions. This is used in many built in functions
max(3,5)
max([1,2,3,4,5,6])
max(["one", "two", "three"])
max(["one", "two", "three"], len)
def volume(radius, height):
return 3.14*radius**2*height
volume(1, 5)
volume(5, 1)
volume(radius=1, height=5)
volume(1, height=5)
volume(radius=1, 5)
def volume1(radius, * , height=5):
return 3.14*radius**2*height
volume1(1)
volume1(1, 5)
volume1(1, height=5)
records = [
("A", 8.9),
("B", 3.4),
("C", 9.0),
("D", 4.0),
("E", 3.8)
]
max(records)
def get_score(record):
return record[1]
max(records, key=get_score)
records[0]
records[-1]
r = records[0]
r
r[1]
r[0]
string
book = "Alice in wonderland"
book.lower()
book.upper()
len(book)
book.endswith("land")
book.startswith("Alice")
book.count("i")
book.count("d")
book.split()
words = book.split()
"_".join(words)
problem: Write a function to find number of zeros in a given number.
count_zeros(1000)
3
def count_zeros(x):
return str(x).count('0')
count_zeros(1000)
count_zeros(2**10000)
lists
numbers = list(range(5, 25, 2))
numbers.count(5)
numbers.reverse()
numbers
numbers.reverse()
numbers
numbers.append(25)
numbers
numbers.pop()
numbers
numbers.pop(0)
numbers
numbers.insert(0, 5)
numbers
numbers.push()
len(numbers)
numbers.drop(5)
numbers.sort()
numbers
numbers.sort(reverse=True)
numbers
sorted(numbers)
numbers
names = ["tilak kamod", "bhimpalas", "yaman", "bageshri"]
names.extend(["durga", "bhoopali"])
names
numbers
numbers.insert(23, 7)
numbers
numbers[-1]
numbers.insert(100, 56)
numbers
numbers[100]
numbers[:100]
tuples
tigits = (1, 2, 3, 4, 5, 6, 7, 8, 9)
tigits.count(2)
tigits.index(5)
numbers[0] = 25
numbers
tigits[0]
tigits[0] = 4
problem: write a function head that takes a list and n , and returns first n items from the list
head(["python", "lisp", "ruby", "haskell", "java"], 2)
["python", "lisp"]
problem: Write a function rearrangemax that takes integer as an argument and returns a new integer with digits rearraged from max to min
rearrangemax(436218)
864321
def head(items, n=2):
return items[:n]
def tail(items, n=2):
return items[n+1:]
head(["python", "lisp", "ruby", "haskell", "java"])
tail(["python", "lisp", "ruby", "haskell", "java"])
n = 56456878
strnum = str(n)
strnum
sorted(strnum, reverse=True)
"".join(sorted(strnum, reverse=True))
int("".join(sorted(strnum, reverse=True)))
def rearrangemax(n):
ordereddigits = sorted(str(n), reverse=True)
return int("".join(ordereddigits))
rearrangemax(34534543543)
import math
def area_circle(r):
return math.pi * r**r
math
import math as m
m
import sys
sys
sys.argv
math.sqrt(343)
math.pi
m.pow(3.4, 5)
m.pi
import os
os.getcwd()
os.getenv("HOME")
os.mkdir("/tmp/test1")
!ls /tmp/
os.listdir(os.getcwd())
os.path.exists("/tmp/test")
os.path.exists("/tmp/test1")
os.path.getsize("./day1.html")
problem:
countfiles which counts number of files in given directorybiggestfile to find biggest file in given given directory.def countfiles(path):
return len(os.listdir(path))
countfiles(os.getcwd())
def biggestfile(path):
files = os.listdir(path)
return max(files, key=os.path.getsize)
biggestfile(os.getcwd())
%%file mymodule.py
def say_hello(name):
print("hello", name)
import mymodule
mymodule.say_hello("python")
%%file mymodule1.py
import sys
def say_hello(name):
print("hello", name)
say_hello(sys.argv[1])
!python mymodule1.py python
!python mymodule1.py java
import mymodule1
%%file module.py
print(__name__)
import module
!python module.py
%%file module1.py
def add(x,y):
return x+y
def hello(name):
print("hello", name)
import module1
module1.add(3,4)
%%file arguments.py
import sys
def print_arguments():
"""
prints system arguments
"""
print(sys.argv)
if __name__ == "__main__":
print_arguments()
import arguments
!python arguments.py hello arg1 arg2 arg3
help(os.listdir)
help(arguments.print_arguments)
import random
random.choice(["python", "java", "haskell", "lisp", "ruby"])
problems:
%%file square.py
import sys
def square(x):
return x*x
if __name__ == "__main__":
print(square(int(sys.argv[1])))
!python square.py 5
import square
square.square(65)
%%file echo.py
import sys
def echo(args):
print(" ".join(args))
if __name__ == "__main__":
echo(sys.argv[1:])
!python echo.py hello this is echo command
__name__ == "__main__"
2 == 2
1 > 2
1.99 <= 2
2 !=3
"python" > "c++"
"alice" in "alice in wonderland"
"this" is not "english"
"alex" not in "alice in wonderland"
book
book.endswith("land")
book.startswith("Alice")
if book.startswith("Alice"):
print(book)
elif book.endswith("something"):
print("elif1")
elif "python" in ["python", "c++", "ark"]:
print("elif2")
elif True:
print("you can have long list of elifs")
else:
print("Finally end with else")
emptylist = []
emptydict = {}
emptystr = ""
if emptylist:
print("Not here")
else:
print("yes here!")
noneobject = None
if not noneobject:
print("Yes it is None")
def is_python_file(filename):
return filename.endswith(".py")
is_python_file("mymodule.py")
filename = "hello.py"
if is_python_file(filename):
print(filename, "is python source file.")
else:
print(filename, "is not python source file.")
def even(n):
return n%2==0
def odd(n):
return not even(n)
problem
filetype which determines type of file. file types supported by your function are listsed below
type extension
java .java
python .py
haskell .hs
c .c
text .text
>>> filetype("square.py")
python
>>> filetype("square.txt")
text
minimum without using built in min! to find minimum of given two numbers
>>> minimum(2,3)
2
>>> minimum3(1,2,3)
1
2 == 2 and 2 !=3
2==2 or 2==3
def filetype(filename):
if filename.endswith(".java"):
return "java"
elif filename.endswith(".py"):
return "python"
elif filename.endswith(".hs"):
return "haskell"
elif filename.endswith("c"):
return "c"
elif filename.endswith("txt"):
return "text"
else: return "Unknown"
filetype("hello.dffdf")
def minimum(x, y):
if x <y:
return x
else:
return y
def minimum3(x,y,z):
return minimum(minimum(x,y), z)
primes = [2, 3, 5, 7, 11, 13, 17]
5 in primes
primes2 = primes
primes2 == primes
primes2 is primes
primes3 = [2, 3, 5, 7, 11, 13, 17]
primes2 == primes3
primes2 is primes3
person = {"name":"robinson",
"books":["Element", "Finding your element"],
"language":"English"
}
"robinson" in person
"name" in person
"robinson" in person.values()
def print_fibonacci(n):
"""
print sequence of fibonacci numbers less than n
"""
prev, current = 1, 1
while current < n:
prev , current = current, prev+current
print(prev, end=",")
print_fibonacci(25)
print_fibonacci(100)
items = primes
for item in items:
print(item, end=",")
range(10)
for i in range(10):
print(i, end=",")
for name in ["elsa", "alice", "alex", "anand"]:
print(name)
for c in "this is a string to test for loop over chars":
print(c, end=",")
for i in range(2, 50, 5):
print(i, end=",")
problem:
write a python script ls.py which mimics unix command ls. i.e. it prints all the files in given directory
python ls.py
arguments.py
day1.html
day1.ipynb
write a function product that finds product of all items from given sequence.
factorial function!ls
def product(numbers):
p = numbers[0]
for num in numbers[1:]:
p = p*num
return p
product([2,3,4])
product(range(1,5))
def fact(n):
return product(range(1, n+1))
factorial = lambda n : product(range(1, n+1))
factorial(10)
factorial(4)
fact(5)
factorial(5)
def print_primes(n):
for i in range(1, n+1):
for j in range(2,i):
if i%j==0:
break
else:
print(i, end=",")
print_primes(100)
numbers = list(range(10))
numbers[1:6:1] #start at index 1 end at 6(exculsive) at step of 1
numbers[1:6]
numbers[:6] #starts at zero and ends at 6
numbers[6:] #starts at 6 ends at end
numbers[:100]
numbers[::-1]
numbers[:]
numbers[:-1] # all except last
numbers[:-2] # all till second last
word = "madam"
is_palindrome = lambda w : w==w[::-1]
is_palindrome(word)
problem:
>>> evens([1,2,3,4,5,6,7,8,9])
[2,4,6,8]
split_at which will split given list in two parts, one before given index and one after the index
>>> split_at([0,1,2,3,4,5,6,7,8], 2)
([0,1], [2,3,4,5,6,7,8])
find_extension to find extension of a file, given file name.
>>> find_extension("python.exe")
exe
def evens(numbers):
evens_ = []
for n in numbers:
if n%2 == 0:
evens_.append(n)
return evens_
evens(range(20))
def split_at(items, index):
return items[:index], items[index:]
def find_extension(filename):
return filename.split(".")[-1]
find_extension("anaconda.tar.gz")