Python

Python is a high-level, general-purpose, interpreted, dynamic programming language. Python supports Boolean, integer, float ,string many other data types. Lanuage support usual flow control syntax like for, while, if, else, continue, break etc and arithmetic operator and logical operator.

Some inbuilt function and important flow control syntax

https://docs.python.org/2/library/functions.html

range


In [ ]:
# range(start, stop[, step]) The arguments must be plain integers
result = range(10)
print(result)
print(range(10, 20, 2))

In [ ]:
print(type(result)) # it return list type. We will talk about it later. it is just sequence of items
print(type(result[0]))

In [ ]:
# in general to see the syntax use ? or ??. ipython or jupyter notebook support tab completion
range?

In [ ]:
# you can press <Shift>-<Tab> to get a tooltip showing the function's signature in notebook

for loop


In [ ]:
#for <variable> in <sequence>:
#<statements>

for item in range(10):
    print('item {} item square {}'.format(item, item*item))

Basic Data

We will be manily interested in these

  • List
  • tuple
  • Dictionary

List

To create a sequence of values

  • We generally use list to store several values for same type of data like list of integers, list of strings etc.
  • List are useful when we want o modify the content like adding or deleting

In [ ]:
x = [1, 3, 5, 10] 
print(x[0]) # list is 0 index based
print(x[3])

list support append, insert and remove


In [ ]:
y = list() # same as y = [], syntactic sugar
y.append('red') 
y.append(10) # it is heterogenuous collection of item
print(y)

Via list comphrehension


In [ ]:
# [<some_func>(x) for x in <something> if  <some_condition_is_true>]
square_list = [x*x for x in range(10)]
print(square_list)

In [ ]:
even_number_square_list = [x*x for x in range(10) if x%2 ==0]
print(even_number_square_list)

Excercise 1: use for loop and list to build cubic list of number from 0 to 10 including

tuple

tuple are use to aggregate dfferent piece of data in one container. Tuple are immutable. So we can't modify their content

Creating tuple


In [ ]:
our_galaxy = ("Milky Way ", "100,000-120,000", 200, 100) # name, diameter, stars, planets
print(our_galaxy)
print(our_galaxy[0])

tuple unpacking


In [ ]:
name, diameter, stars, planets = our_galaxy # tuple unpacking
print(planets)

One of the major disadvantage is their readability. What is the third poition of a tuple. Can guess from context, but is hard in general if there are lot element in tuple.

Name tuple come to rescue in this situation. no covering in this workshope

Dictionaries

Dictionaries allows mapping object to other objects i.e they store key valye pair. They are extremly efficient in look up based on key.

They are also go to pass variable number of parameters in the functions.

Key: value used for index

Value stored value

creating dictionaries


In [ ]:
algoConfig = {} # can use nameAgeDic = dict()
algoConfig['threshold'] = 20 # in pixel
algoConfig['neighborhoodSize'] = 4 # 4X4 neighborhood
algoConfig['tolerance'] = 0.002 # convergence tolerance
print(algoConfig)

some syntactic sugar


In [ ]:
charValDict = {'a':2, 'b': 10, 'c':54}
print charValDict
print charValDict['b']

All the keys and values in dictionaries


In [ ]:
print(charValDict.keys())
print(charValDict.values())
print(charValDict.items())

Using directionary comprehension


In [ ]:
studentScore = [['John', (10, 20 )], ['sam', (30, 50)] , ['paul', (40, 20)]]
finalScoreDict = {  name: sum(score) for  name, score in studentScore }
print(finalScoreDict)

Sets

Set are simiar to mathematical set. They represent collection of unique things. we can check set cardinality, set membership, union, intersection etc.


In [ ]:
nameSet = set() # empty set
ageSet = set([10, 20, 5])
print(ageSet)
ageSet.add(15)
print('set after adding {} is {}'.format(15, ageSet))
print('Cardinality of set is {}'.format(len(ageSet))) #cardinality of set
10 in ageSet # membership

Excercise: Supose we have following dictioney of instructor name: course taught What are the different course taught in the department?


In [ ]:
instructorCourseLibrary = {'Dr. Mohammad Mahoor': ['Machine learning', 'VLSI Design', 'linear lagebra'],
                           'Dr. KIMON VALAVANIS':[ 'Pattern Recognition', 'statistics'] ,
                           'Dr. GEORGE EDWARDS':['VLSI Design', 'Pattern Recognition'] }

writing function


In [ ]:
def calculate_l2_norm_square_of_vector(vec):
    sum = 0
    for item in vec:
        sum = sum + item*item
    return sum

In [ ]:
print(calculate_l2_norm_square_of_vector([1,2]))

writing variable number of arguments function


In [ ]:
def logInfo(level, *args ):
    print level
    print args
    for arg in args:
        print(arg)
        
logInfo(1, '9 Nov', 'Denver', 75 )

Actually these variable number of arguments are packed into a tuple.

Using *operator we can do the opposite i.e unpack the argument out of a list or tuple

Similary for passing variable length keyword argument use following syntax


In [ ]:
def logInfoKeyWord(level, **kwargs ):
    print level
    print kwargs
    for key , val in kwargs.items():
        print('key = {} value = {}'.format(key, val))
        

logInfoKeyWord(1, Date= '9 Nov', City = 'Denver', Temperature=75)

Or we can use ** operator on a dictionary to get keyword arguments


In [ ]:
params = {'Date': '9 Nov', 'City' : 'Houston', 'Temperature':75} 
logInfoKeyWord(1, **params )

Before the variable number of arguments, zero or more normal arguments may occur. if we use both then *args must occur before **kwargs

Python with battery included (standard library)

Python comes some built in function like print, len etc and a set of modules called standard library. A module is set of related python function like math, random, numpy, scipy, matplotlib etc. To use a module you has to first import it using one of following syntax.

https://docs.python.org/2/library/

https://docs.python.org/3/library/


In [ ]:
import math
math.sin(math.pi/2)

or


In [ ]:
import math as mt
mt.sin(mt.pi/2)

In [ ]:
from math import sin, pi

sin(pi/2)

In [ ]:
import numpy as np

x = np.array([[1, 4 ,8],[ 3 , 4, 6]])
print(x)

slicing numpy array is similar to MATLAB


In [ ]:
print(x[1,1:])

In [ ]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10)
line, = plt.plot(x, np.sin(x), '--', linewidth=2)
plt.show()

Most of the the scientifc work is driven by numpy, scipy,sympy, matplotlib, bokeh, pandas and

domain specific packages like