Oct 16-18, 2017 Vikrant Patil
These notes are available online at http://notes.pipal.in/2017/vmware-oct-python
© Pipal Academy LLP
0 #python has basic datatypes... integers
0 + 2
1.2 # it has floats
x = 3
print(x)
name = "krishna"
name
print(name)
2 + 2 # addition
2 * 2 #multiplication
2 ** 3 # power
13 % 10 # divmod
2 ** 100
2 ** 1000 # it supports really big numbers
5 / 2 # division
5 //2 # integer division
0.001 + 1
1.1 - 1.0
Python has strings with lots of useful features
first = "Rupali"
second = "Rupak"
first
second
first + second
print(first, second)
fullname = first + " " + second
print(fullname)
s = 'string with single quote'
print(s)
double = 'string with " double quote'
print(double)
single = "string with ' single quote"
print(single)
fullname = "Rupali" "Rupak"
print(fullname)
five = str(5)
print(five)
five
star = "*"
5*star
"*"*20
string supports escape characters
twolines = "first line \nsecond line"
print(twolines)
multiline = """
this is
a multiline
string
which can have
any number
of lines
"""
print(multiline)
regional = "आ ञ"
len(regional)
print(regional)
print("\u0c85\u0c86")
Python has special type bytes to represent binary data
binary = b'binary'
print(binary)
hex(ord('b'))
hex(145)
ord("b")
hex(98)
binary = b'\x62\x69\x6e\x61\x72\x79'
print(binary)
There is very useful high level data type called 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
letters[2]
letters[3]
mixedtypes = [1, 1, 2, 'x', 'y']
print(mixedtypes)
mixedtypes[0] = "zero"
mixedtypes
len(mixedtypes)
List objects have special indexing mechanism by which you can access elements very easily
topten = [0,1,2,3,4,5,6,7,8,9]
topten[-1] # last element
topten[-2] #second last element
topten[:2] # take first two elements
topten[2:] #drop first two elements
topten[3:7] # from 3rd index(included) till 7th index(excluded)
topten[0:5]
topten[1:8]
matrix = [[1,2,3], [4,5,6], [7,8,9]]
matrix[0] # 0th row
matrix[-1] # last row
matrix[0][0]
matrix[0][2]
There is another datatype similar to lists is tuple
point = (1.1, 2.0)
point[0]
point[-1]
triangle = ((0,0), (0,1), (1,1))
triangle[0]
triangle[0] = (1,2)
ones = (1, 1, 1)
ones + ones
ones*5
print
s = "Just to make sure that \n you undestrand new line"
s
print(s)
pre = "Isac"
post = "Asimov"
name = pre post
_
2 ** 2
_
a = 5*6
a
_
_ = 67
a/6
_
31//6
_
Dictionaries are named collection of objects.
person = {'name':"Alice", "email":"alice@wonder.land", "age":15}
person['name']
person['email']
Python also has set
paragraph = """
lets write some dummy python fiction
to create set. and try to find out how
many alphabets are used in
this
"""
alphabets = set(paragraph)
alphabets
And offcourse you talk about True and False in python
sure = True
arrr = False
print(sure, arrr)
There is special object for nothing!
nothing = None
len("python") # len works on string
len([1,2,3,4]) # len works on lists
len((2,3,45,4)) # len works on tuple
len({'a':1, 'b':2})
4 + "2"
4 + int("2")
str(4) + "2"
problem: Using the functions above , is it possible to find number of digits in a given number? lets say 2**1000
digits = str(2**1000)
len(digits)
def square(x):
return x*x
def say_hello(name):
print("hello", name)
square(5)
say_hello("HARI")
value = square(5)
value
value = say_hello("Hari")
value
print(value)
Problem : Write a function count_digits that counts number of digits of a given number
count_digits(100)
3
count_digits(1000)
4
Problem: Before you try out following code , guess what will be output?
def twice(x):
return 2*x
def twice1(x):
print(2*x)
twice(twice(2))
twice1(twice1(2))
Functions in python are just like other data types. They are ordinary in that sense. But that makes them powewrful! lets see how?
def f(x):
return 2*x
f
type(f)
f(2)
twotimes = f
twotimes
type(twotimes)
twotimes(3)
What is the advantage of having this functionality... able to alias functions as variables
def summation(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)
sumof(square, 3, 4)
sumof(cube, 2, 3)
Some in built functions in python take functions as argument.
max(0, 42)
max([1,2,3,4,5])
max(["one", "two", "three", "four"])
max(["one", "two", "three", "four"], key=len) # longest word
min(["one", "two", "three", "four"], key=len) # shortest word
We have a record of scores of students saved as list of tuples. every tuple stores names and score. we wish to find a record with maximum score
scoresheet = [('vijay', 8.8),
('vinay', 8.9),
('vijaya', 9.0),
('vilas', 7.8),
('vishakha', 6.0)]
def get_score(record):
return record[1]
max(scoresheet, key=get_score)
min(scoresheet, key=get_score)
x, y = (1,2)
x
y
def get_score(record):
name, score = record
return score
max(scoresheet, key=get_score)
built in objects have usefull functions built in as part of object. Such functions are called methods
book = "Alice in wonderland"
book.lower()
book.upper()
book.count("n")
book.split(" ")
book.replace(" ", "_")
"_".join(["Alice", "in","wonderland"])
book.startswith("Alice")
book.center(50)
Problem: write a function which will count number of zeros in given number
count_zeros(100)
2
count_zeros(1000)
3
def count_zeros(x):
digits = str(x)
return digits.count("0")
count_zeros(1000)
numbers = list(range(5, 25, 2))
numbers
numbers.count(5)
numbers.reverse()
numbers
numbers.append(3)
numbers
numbers.pop()
numbers
numbers.pop(0)
numbers.sort()
numbers
numbers.sort(reverse=True)
numbers
numbers[0] = 23
numbers
numbers[3] = 21
numbers
names = ["bhairavi", "durga", "asawary", "kalashree", "bhupali", "tilak kamod"]
names.sort()
names
names.sort(key=len)
names
names.extend(["yaman", "malkauns"])
names
tuples
numbers = (1,1,2,3,4)
numbers.count(1)
numbers.index(1)
problem:
head that takes a list of words and returns first n words by dictionary order
>>> words = ['python', 'lisp', 'haskell', 'ark', 'java', 'ocamel']
>>> head(words, 3)
['ark', 'haskell', 'java']
count_words that takes a sentence or a string as an argument and returns number of words it has.
>>> count_words("life is 42")
3
words = ['python', 'lisp', 'haskell', 'ark', 'java', 'ocamel']
words.sort() # this sorts list in place
sorted(words) # this returns a new sorted list
def head(words, n):
words_sorted = sorted(words)
return words_sorted[:n]
def head1(words, n):
words.sort()
return words[:n]
head(words, 4)
head1(words, 3)
def count_words(sentence):
words = sentence.split(" ")
return len(words)
count_words("Count words from this sentence")
For convinience related functions are organised inside a module. python's built in modules can be imported and used as given below
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)
polar_to_rectangular(1, math.pi/2)
x , y = polar_to_rectangular(1, math.pi)
print(x, y)
import os
os.getcwd() # current working directory
os.getenv("HOME")
os.mkdir("/tmp/test")
!ls /tmp/t*
os.listdir(os.getcwd())
os.path.exists("/tmp/test")
os.path.getsize("day2.html")
problem:
countfiles which takes directory path as argument and returns number of files in that directorybiggestfile to find biggest file in a given directoryimport os
def countfiles(dirpath):
return len(os.listdir(dirpath))
def biggestfile(dirpath):
files = os.listdir(dirpath)
return max(files, key=os.path.getsize)
countfiles(os.getcwd())
biggestfile(os.getcwd())
import math as m
m.pi
m.sin(3.14)
from math import sin
sin(3.14)
from os.path import getsize
getsize("./day1.html")
%%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
!python mymodule1.py argument1 argument2 hello 2 3 4
problem:
%%file square.py
import sys
def square(x):
return x*x
v = int(sys.argv[1])
print(square(v))
!python square.py 2
import os
help(os.path.getsize)
import square
square.square(4)
%%file arguments.py
import sys
def print_arguments():
"""
prints system arguments
"""
print(sys.argv)
import arguments
help(arguments)
%%file main.py
def hello():
print("Hello")
hello()
import main
def func(x):
print("Hello")
return x*x
%%file main1.py
def hello():
print("Hello")
print(__name__)
import main1
!python main1.py
%%file main2.py
def hello():
print("Hello")
if __name__ == "__main__":
hello()
import main2
!python main2.py
import random
random.choice(['python', "java", "haskell", "lisp"])
How do I pick up a random word from a sentence
sentence = "some random statement with random words"
random.choice(sentence.split())
problem:
%%file add.py
import sys
def add(x, y):
"""
docstring of add ... just adds two numbers
"""
return x+y
if __name__ == "__main__":
a = int(sys.argv[1])
b = int(sys.argv[2])
print(add(a, b))
!python add.py 3 4
import add
help(add)
%%file echo.py
import sys
def echo(x):
print(x)
if __name__ == "__main__":
s = " ".join(sys.argv[1:])
echo(s)
!python echo.py echo command equivalent
1 > 2
1.99 <= 2.0
2 != 3
2 == 2
2 <= 2
"python" > "c++"
"alice" in "alice in wonderland"
"alice" not in "alice in wonderland"
book = "alice in wonderland"
book.endswith("land")
book.startswith("alice")
def is_python_script(filepath):
return filepath.endswith(".py")
is_python_script("hello.py")
is_python_script("hello.java")
python = [3.4, "if"]
if "if" in python:
print("Obviously it has if")
elif python[0] > 3:
print("Python version is 3")
elif True:
pass
else:
print("If none of the if or elifs got executed..it will come here")
def even(n):
if n%2 == 0:
return True
else:
return False
even(2)
The conditional after if will be True for
def even(n):
return not n%2
even(3)
def odd(n):
return not even(n)
odd(3)
problem:
filetype which takes filename as argument and returns file type. type extension
python .py
text .txt
c .c
java .java
>>> filetype("square.py")
python
>>> filetype("hello.txt")
text
>>> minimum(3,4)
3
>>> minimum3(1,2,3)
1
def minimum(x,y):
if x < y:
return x
else:
return y
minimum(4,5)
def minimum3(x,y,z):
return minimum(minimum(x,y),z)
minimum3(4,5,7)
primes = [2,3,5,7,11,13,17]
5 in primes
primes2 = primes
primes is primes2
primes == primes2
primes3 = list(primes)
primes3 == primes # this checks values
primes3 is primes # this checks reference
person = {"name":"robinson",
"books":["Element", "Finding your element"],
"TED":"How schools kill creativity"
}
"name" in person
"robinson" in person
"robinson" in person.values()