Sep 18-20 2017 Vikrant Patil
These notes are available online at http://notes.pipal.in/2017/vmware-python
© Pipal Academy LLP
1
1.2
x = 3
x
print(x)
name = "krishna"
print(name)
raga = input()
print(raga)
2 + 2
2 - 3
2 * 3
2 ** 3
9 % 2
2 ** 100
2 ** 1000
5 // 2
5 / 2
0.0001 + 1
first = "Rupali"
second = "Rupak"
print(first, second)
"Rupali" "Rupak"
name = "Rupali" "Rupak"
name
first + second
name = first + " " + second
name
five = str(5)
five
star = "*"
fivestar = star * 5
fivestar
print("*"*50)
It also supports usual escape chars
twolines = "first line \n second line"
print(twolines)
columns = "column1\tcolumn2"
print(columns)
multiline = """
pthon is very simple
python is very powerfull
python is very close to human language , english
and it has nothing do with snakes, but it is related
BBC's monty python show
"""
multiline
print(multiline)
print("\u0c85")
print("I can have ' single quote inside")
print('I can have " double quote inside')
'something'
It has binary data
binary = b'binary'
print(binary)
hex(5)
hex(ord("b"))
binary = b'\x62\x69\x6e'
print(binary)
High level data type called lists
letters = ['a','b','c']
letters
letters[0]
letters[1]
len(letters)
ones = [1,1,1,1]
moreones = ones + ones
moreones
multidata = ["a", 1, "Three", ones]
multidata
multidata[0]
multidata[2]
multidata[3]
multidata[0] = "b"
multidata
topten = list(range(10))
topten
topten[-1]
topten[-2]
topten[:2]
topten[2:]
topten[5:7]
someotherlist = ['a', 'b','c','d','e']
someotherlist[0]
someotherlist[2:4]
someotherlist[1:4:2]
someotherlist[1:4:-1]
someotherlist[4:0:-1]
len(someotherlist)
someotherlist[1:4][-1]
someotherlist[::-1]
matrix
matrix = [[1,2,3], [2,3,4],[5,6,7]]
matrix
matrix[0]
matrix[-1]
matrix[0][-1]
There is a sibling of list caleed tuple. tuple is just like list, but immutable.
point = (1.1, 2.0)
point[0]
point[1]
traingle = ((0,0),(0,1),(1,1))
traingle[0]
traingle[0] = (0,3)
ones = (1,1,1)
ones + ones
ones
ones + ones
mutable = list(ones)
mutable
mutable[0] = 0
mutable
ones
Dictionaries are named collection of objects. You retrive objects aby names instead of index
machine = {"name":"mozart", "os":"ubuntu", "make":"acer"}
machine
machine['name']
machine['os']
machine["key"] = 5
machine
machine
set :Python has datatype set which allows us to store data as a set.
paragraph = """
I have random fiction
written for this trp aining
and we want to find how many english charecters are used in it
"""
set(paragraph)
set([2,2,3,4,5,6,7,8,11,11,12,13])
and offcourse boolean
sure = True
arrr = False
print(sure, arrr)
There is one very special object for nothing!
nothing = None
print(nothing)
nothing
a = {1,2}
a
a = {[1,2,3], [1,2,3]}
pre = "Isac"
post = "Asimov"
name = pre post
_
2 ** 2
_
a = 5 * 6
_
_ = 67
a/6
_
31 // 6
Lets see some built in functions
len("Python")
len((1,2,3,4))
len([1,2,3,4,5,6,7])
len({"a":1})
len(set("Hello"))
4 + "2"
str(4) + "2"
Problem : Using known functions find out number of digits in 2**100
len(str(2**100))
digits = str(2**100)
digits
len(digits)
def square(x):
return x*x
def say_hello(name):
print("Hello", name)
square(5)
say_hello("hari")
s = square(5)
s
r = say_hello("hari")
r
print(r)
say_hello(5)
print("Hello{}".format("hari"))
count_digits to count number of digits in a given number.
count_digits(100)
3
def twice(x):
return 2*x
def twice1(x):
print(2*x)
twice(twice(3))
twice1(twice1(3))
Functions in python are nothing special as compared to other data types. but makes it very special
def func(x):
return x*x
print(func)
print([1,2,3])
type([1,2,3])
type(1)
type(func)
f = func
func(2)
f(2)
print(f)
print(func)
def summation(x,y):
return x+y
def square(x):
return x*x
def sumaofsquares(x, y):
return square(x) + square(y)
def cube (x):
return x**3
def sumofcubes(x,y):
return cube(x) + cube(y)
def sumof(x, y, f):
return f(x) + f(y)
sumaofsquares(2,3)
sumof(2, 3, square)
def cube (x):
return x**3
def square(x):
return x*x
def sumof(x, y, f):
return f(x) + f(y)
sumof(2,3, cube)
sq = lambda x: x*x
sumof(2,3, sq)
def make_adder(y):
return lambda x: x+y
add2 = make_adder(2)
print(add2)
add2(10)
There are some built in functions which take functions as argument
max(4,5)
max([1,2,3,4,5])
max(["one", "two", "three", "four", "five"])
words = ["one", "two", "three", "four", "five"]
max(words, key=len)
min(words, key=len)
We have record which contains scores of students stores as tuple in a list. We wish to find a student with max score.
scroresheet = [("vinay", 8.8, 14),
("vijay", 9.0, 14),
("vijaya", 9.9, 13),
("vishakha", 9.1, 12)]
def get_score(record):
return record[1]
max(scroresheet, key=get_score)
max(scroresheet)
max(scroresheet, key= lambda r:r[1])
Objects of built in data type has some usefull functions as part of object. Those are called methods
string
book = "Alice in wonderland"
book.lower()
book.upper()
book.count('n')
book.split(" ")
book.replace(" ","_")
book.startswith("Alice")
book.endswith("alice")
lists
numbers = list(range(5,25,2))
numbers
numbers.count(5)
numbers.count(" ")
numbers.reverse()
numbers
numbers.append(0)
numbers
numbers.pop()
numbers
numbers.sort(reverse=True)
numbers
names = ['asawary', 'bahiravi','kalashri','tilak kamod']
names.sort()
names
names.sort(reverse=True,key=len)
names
names.extend(['yaman', 'malkauns'])
names
tuple
numbers = (1,2,3,4)
numbers.count(1)
numbers.index(3)
Write a function to count zeros in a given number
count_zeros(100)
2
Write a function head that takes list of words and returns first n words by dictionary order
head(['python','lisp', 'haskell', 'ocamel','ark', 'java'], 3)
['ark', 'haskell', 'java']
def count_zeros(n):
return str(n).count('0')
def head(words, n):
words.sort()
return words[:n]
count_zeros(2**100)
head(['python','lisp', 'haskell', 'ocamel','ark', 'java'], 3)
For convinience related functions are organised inside a module. you can import these modules make use of functions or objects from that module
import math
def area_circle(radius):
return math.pi * radius * radius
def polar_to_ractangular(radius, theta):
return radius*math.cos(theta), radius*math.sin(theta)
area_circle(1)
polar_to_ractangular(1, math.pi/2)
x,y = polar_to_ractangular(1, 0)
x, y
x, y = y , x
x, y
import os
os.getcwd()
os.getenv("PATH")
os.getlogin()
os.mkdir("/tmp/test1")
!ls /tmp/
os.listdir("/tmp/")
os.path.exists("/tmp/test1")
os.path.getsize("./Makefile")
countfiles to count number of files in a given directorybiggestfile to find biggest file in a given directorydef biggestfile(directory):
files = os.listdir(directory)
return max(files, key=os.path.getsize)
biggestfile(os.getcwd())
custom modules can be written by writing python statements and functions inside file with extension .py
%%file mymodule.py
import sys
def say_hello(name):
print("Hello ", name)
print(sys.argv)
!python mymodule.py
!python mymodule.py hello 1 2 3
import mymodule
mymodule.say_hello("Python")
help(mymodule)
import random
random.choice(["python","lisp","haskell", "java"])
random.choice(["python","lisp","haskell", "java"])
senestence = "Pascal traingle is very simple structure but it has got very interesting properties"
random.choice(senestence.split())
%%file square.py
import sys
def square(x):
return x*x
x = int(sys.argv[1])
value = square(x)
print(value)
!python square.py 3
%%file echo.py
import sys
print(sys.argv[1:])
!python echo.py echoes this statement till end
"_".join(["hello", "world", "make", "statement"])
%%file echo.py
import sys
print(" ".join(sys.argv[1:]))
!python echo.py echoes this statement till end
there is special variable __name__
%%file anothermodule.py
print(__name__)
!python anothermodule.py
import anothermodule
%%file echo.py
import sys
def echo():
x = 0
print(" ".join(sys.argv[1:]))
print(__name__)
if __name__ == "__main__":
echo()
import echo
!python echo.py some commandline arguments