Oct 25-27, 2017 Vikrant Patil
These notes are available online at http://notes.pipal.in/2017/arcesium-oct-python/day1.html
© Pipal Academy LLP
2 + 3
x = 3
x
x
print(x)
name = "Krishna"
print(name)
raga = input()
print(raga)
print("Hello", name)
There are integers
2 + 2
2 * 2
2 - 4
2 ** 5
8 % 2
2 ** 1000 # integers can be big!
5 / 2
5 // 2
Python has floats
0.0001 + 1
Python has string
first = "Rupali"
second = "Rupak"
print(first, second)
name = first + " " + second
print(name)
name = "Rupali" "Rupak"
name
five = str(5)
print(five)
five
star = "*"
rating = star *5
rating
print("="*30)
twolines = "first\nsecond\nthird"
print(twolines)
multiline = """
first
second
third
"""
print(multiline)
s = "what's your name?"
print(s)
singlequote = 'in this string i can put double "'
print(singlequote)
multi = '''
multiline
with
signle quote
'''
print(multi)
regional = "आ ष"
print(regional)
print("\u0c85\u0c86")
Python has binary data reprersentation as bytes
binary = b'binary'
print(binary)
hex(ord("b"))
binary = b'\x62\x69\x6e\x61\x72\x79'
print(binary)
There are special high level data types like list
letters = ['x','y','z']
letters[0]
letters[1]
letters[2]
len(letters)
ones = [1, 1, 1, 1]
moreones = ones + ones
moreones
stillmoreones = ones * 5
stillmoreones
mixedtypes = ["one", "two", 1, 2]
mixedtypes
mixedtypes[0] = "zero"
mixedtypes
List has special mechanism to index various items
topten = [0,1,2,3,4,5,6,7,8,9]
topten[-1]
topten[-2]
print(topten)
topten[:2] #take first two elements
topten[2:] # drop first two elements
head = topten[:2]
print(head)
tail = topten[2:]
print(tail)
tail
topten
matrix = [[1,2,3],[4,5,6],[7,8,9]]
matrix[0] # 0th row
matrix[1] # 1st row
matrix[0][-1] # last element in 0th row
matrix[-1]
matrix[0] = [7,8,9]
matrix
There is another datatype similar to lists...called tuple ..
point = (1.1, 2.0)
print(point)
triangle = ((0,0), (0,1), (1,1))
triangle[0] = (0,0.5)
ones = (1,1,1)
ones*5
ones + ones
manyobjects = ((1,1,1), "one", ('a','b','c'))
t = (1,2,3, (1,1,1), [0,0,0])
t[2]
t[4]
t[4] = [3,4,5]
t[4][0] = 1
t
t[:2]
t[2:]
t[-1]
Dictionary is named collection of objects
data = {"one":1, "two":2, "three":3}
data["one"]
machine = {"name":"mozart", "os":"mint", "brand":"acer"}
machine['name']
machine['os']
d = {"names":["alice", "alex","david"]}
d['names']
Set
paragraph = """
1 some random text
2 to see how many english aphabets
3 are being used while writing this
4 if I have some numbers in it
"""
set(paragraph)
set([1,2,1,1,2,3])
And of course there are booleans
sure = True
arrr = False
print(sure, arrr)
There is one more type for nothing
nothing = None
print(nothing)
s = "Just to make sure , \nthat you understand new line"
s
print(s)
pre = "Isac"
post = "Asimov"
name = pre post
p = "Isac"
post = "Asimove"
together = p post
print(name)
s = "some value\n another value"
s
print(s)
len("Python")
len([1,2,3,4,5])
len((1,2,3,4,5,56))
len({"jan":31, "feb":28,"Mar":31})
4 + int("2")
str(4) + "2"
Problem Using the function we know as of now, find number of digits in a given number. lets say 2 ** 100
digits = str(2**100)
digits
len(digits)
def square(x):
v = x *x
return v
print(square(4))
def say_hello(name):
print("hello", name)
say_hello("Python")
value = square(5)
print(value)
value = say_hello("Hari")
print(value)
Do it yourself
count_digits to count number of digits in given number. it should work as given below
>>> count_digits(2*100)
31
def twice(x):
return 2*x
def twice1(x):
print(2*x)
twice(twice(3))
twice1(twice1(3))
def twice1(x):
print(2*x)
def twice(x):
return 2*x
v = twice(3)
v
v1 = twice1(3)
print(v1)
twice1(None)
def count_digits(number):
digits = str(number)
return len(digits)
count_digits(2**1000)
Functions in python are ordinary just like any ohter data type like integers, floats, lists... But that makes them special
def func(x):
return 2*x
func
print(func)
type(func)
type(4)
type([1,2,3,4])
twotimes = func
func(5)
twotimes(5)
twotimes
type(twotimes)
def sumation(x, y):
return x + y
def square(x):
return x*x
def sumofsquares(x,y):
return square(x) + square(y)
def cube(x):
return x*x*x
def sumofcubes(x,y):
return cube(x) + cube(y)
def sumof(f, x, y):
return f(x) + f(y)
sumofsquares(5,6)
sumof(square, 5, 6)
def make_adder(y):
def add(x):
return x+y
return add
adder5 = make_adder(5)
adder5
adder5(8)
adder5(9)
adder6 = make_adder(6)
adder6(9)
def f(a):
return a+a
f
adder6 = make_adder(6)
adder6
adder6(7)
def add(x,y):
return x+y
f = lambda x,y: x+y
f
f(4,5)
def make_adder(y):
return lambda x : x+y
adder7 = make_adder(7)
adder7(10)
print(f)
type(f)
Passing functions as parameter is so usefull, that in built python functions make use of it at many places
max(0,42)
max([0,1,2,3,5])
max(["one", "two", "three", "four"])# what would be output?
words = ["one", "two", "three", "four"]
max(words, key=len)# this is how I find longest word
min(words, key=len) #this is how I find shortest word
scoresheet = [("vinay",8.8),
("vijay",8.9),
("vijaya",9.0),
("vilas",7.8),
("vishakha",9.1)
]
scoresheet
def get_score(record):
return record[1]
max(scoresheet, key=get_score)
min(scoresheet, key=get_score)
max(scoresheet, key=get_score)[0]
max(scoresheet, key=get_score)[1]
Built in obejcts have udefull functions built in as part of object itself. These functions are called methods
book = "Alice in wonderland"
book.lower()
book.upper()
book.count("n")
book.split(" ")
book.replace(" ", "_")
book
book.replace(" ","_").split("_")
book.startswith("Alice")
book.endswith("land")
numbers = list(range(5, 25, 2))
numbers
numbers.count(5)
numbers.reverse()
numbers
numbers.append(3)
numbers
numbers.pop()
numbers
numbers.pop(0)
numbers
numbers.sort()
numbers
numbers.sort(reverse=True)
numbers
words = ["One","two","Three"]
max(words, key=lambda w:w.lower())
sorted(numbers, key=lambda x:x, reverse=True)
numbers.extend([3,1])
numbers
numbers.index(15)
numbers = (1,1,2,3,5,8)
numbers.count(1)
numbers.index(3)
problem
count_zeros which will count zeros in given number>>> count_zeros(1000)
3
head that takes a list of words and n as an argument and returns first n words by dictionary orderhead(["python", "lisp", "haskell", "ark", "java", "ocamel"], 3)
['ark', 'haskell', 'java']
bonus problem
rearrangemax that takes an integer as an argument and returns a new integer with digits rearranged from max to min.
rearrangemax(43567)
76543
def count_zeros(n):
return str(n).count("0")
count_zeros(1000)
def head(data, n):
return sorted(data)[:n]
head(["python", "lisp", "haskell", "ark", "java", "ocamel"],3)
def rearragemax(n):
digits = str(n)
sorteddigits = sorted(digits, key=int, reverse=True)
return int("".join(sorteddigits))
rearragemax(343524)
import math
def area_circle(radius):
return math.pi*radius*radius
def polar_to_rectangular(radius, theta):
return radius*math.cos(theta), radius*math.sin(theta)
area_circle(1)
x, y = polar_to_rectangular(1, math.pi/2)
print(x, y)
import os
os.getcwd()
os.getenv("HOME")
os.mkdir("/tmp/test1")
!ls /tmp/
print(math)
os.listdir("/tmp/")
math
type(math)
os.path.exists("/tmp")
os.path.getsize("./day1.html")
problem
countfiles to find number of files in given directory.
>>> countfiles("/tmp")
13
biggestfile to find a file of maximum size in given directory.
>>> biggestfile(os.getcwd())
day1.html
def countfiles(location):
return len(os.listdir(location))
def biggestfile(location):
files = os.listdir(location)
return max(files, key=os.path.getsize)
biggestfile(os.getcwd())
%%file mymodule.py
import sys
def say_hello(name):
print("Hello", name)
import mymodule
mymodule.say_hello("Python")
%%file mymodule1.py
import sys
print(sys.argv)
!python mymodule1.py arg1 arg2 arg3
%%file mymodule2.py
import sys
print(sys.argv)
def add(x,y):
return x+y
def mult(x,y):
return x*y
print(mult(3,4))
!python mymodule2.py
%%file circle.py
import sys
a = 3
pi = 3.14
def area(r):
return pi*r*r
def perimeter(r):
return 2*pi*r
radius = float(sys.argv[1])
print("Area of a circle :", area(radius))
print("Perimenter of a circle:", perimeter(radius))
!python circle.py 10 20
%%file rectangle.py
import sys
def area(l, w):
return l*w
def perimeter(l, w):
return 2*(l+w)
length = float(sys.argv[1])
width = float(sys.argv[2])
print("Area of rectangle :", area(length, width))
print("Perimenter of rectangle:", perimeter(length, width))
!python rectangle.py 2 5
import rectangle
%%file main.py
def add(x,y):
return x+y
def sub(x,y):
return x-y
print(__name__)
!python main.py
import main
main.sub(3,4)
main.add(2,3)
from main import add
from os.path import getsize
from math import pi
help(getsize)
help(math)
help(circle)
help(main)
import random
help(random.choice)
sentence = "The beauty of pascal trianlge is that it is simple yet mathematically rich"
random.choice(sentence.split())
random.choice(sentence.split())
help("".split)
problems
%%file square.py
import sys
def square(x):
return x*x
n = int(sys.argv[1])
print(square(n))
!python square.py 4
%%file add.py
import sys
def add(x,y):
return x+y
a = int(sys.argv[1])
b = int(sys.argv[2])
print(add(a,b))
!python add.py 5 6
%%file echo.py
import sys
print(" ".join(sys.argv[1:]))
!python echo.py hello this is echo
a = 2.0 + 3.0
a
import math
import math as m
m
cash = 10000
balance = 50000
def withdraw(balance, amount):
balance = balance - amount
return balance
cash = withdraw(balance, 1000)
print("balance = ", balance)
print("cash =", cash)
withdraw(60000, 2000)
print(balance)
1 > 2
1.99 <= 2.0
2 != 3
2 <= 2
"python" > "java"
"alice" in "alice in wonderland"
"alice" not in "alice in wonderland"
book = "alice in wonderland"
book.startswith("alice")
book.endswith("land")
def is_python_script(filename):
return filename.endswith(".py")
is_python_script("hello.py")
python = [3.4, "if"]
if "if" in python:
print("Obviously python has if")
elif python[0] > 3:
print("python can have long list of elifs")
elif len(python) > 1:
print("still ...long")
else:
print("it will come here if none of above condition is True")
def even(n):
if n%2 == 0:
return True
else:
return False
even(5)
The conditional after if is True for
def even(n):
return not n%2
even(2)
def odd(n):
return not even(n)
odd(3)
Do it yourself
filetype which will take filename as argument and return file type. it should recognise following file types. If filetype is not from given list , it should return None type extension
python .py
java .java
c .c
text .txt
>>> filetype("square.py")
python
>>> filetype("square.txt")
text
minimum (without using in build function min) to find minimum of two numbers
>>> minimum(3,4)
3
minimum3 to find minimum of three numbers
minimum3(2,3,4)
2
def minimum(a,b):
if a < b:
return a
else:
return b
def minimum3(x,y,z):
return minimum(minimum(x,y), z)
minimum3(3,4,5)
primes = [2,3,5,7,11,13,17]
5 in primes
primes2 = primes
primes is primes2
primes == primes2
prime3 = list(primes)
prime3 == primes
prime3 is primes
a = "abcd"
b = a
a.replace("ab", "ef")
a
b
a.sort()