Impacting Education
Python Modules – Module 1
Introduction to Python
Enabling Knowledge Leaders
Impacting Education
Outline/Agenda
● Why Python?
● Motivation to learn Python??
● Installing and Configuring Python(Anaconda
Distribution)
● Data Types & Expressions
● Variables and Assignments
● Branching (if, elif, else)
● Strings & User Input
● Iteration (while Loop, for Loop)
Enabling Knowledge Leaders
Impacting Education
Why Python?
● Simple to program & easy to read and understand
○ Very high level programming language
○ It uses indentation rather than braces
● Powerful, Object Oriented & Cross Platform
● Interpreted Language, easy to work with & debug
● Has many libraries to extend functionality(Generate
plots, edit/read Docx/PDF, move mouse, etc.)
● Examples ➔ Waveform plot
Download .png from Digikey
Enabling Knowledge Leaders
Impacting Education
Motivation to learn Python??
● Easy Syntax
● Beginner Friendliness
● Great Community support
● A Lot Of Great Libraries
● Universal Scripting Language
● The Object-Oriented Aspect
● Growing market for Python programmer
Ref : https://goo.gl/lCAuRv, https://goo.gl/B7MHr6 and
https://goo.gl/ao5rVP
Enabling Knowledge Leaders
Impacting Education
Installing and Configuring Python3
● Install Anaconda package from
Z:\Tools\Programming\Python\Anaconda3-4.1.1-Win
dows-x86_64.exe or
https://repo.continuum.io/archive/Anaconda3-4.1.1-
Windows-x86_64.exe
● Anaconda has many libraries pre-installed
● Anaconda has SPYDER IDE for writing and
executing the codes (spyder.exe)
Enabling Knowledge Leaders
Impacting Education
Notes
● >>> represents the python interpreter prompt. Type the command
you see after it.
● You can manually set spyder as the default environment by adding
this to the PATH variable:
● Python is case-sensitive
● All commands generally start with lowercase characters
● You can install additional packages by running pip install
<package_name> in command prompt
● There are multiple version of Python(1.0, 2.0, 3.0). We will be using
Python 3.5.xx
● indentation has semantic significance in python
● Can be given after the # sign
Enabling Knowledge Leaders
Impacting Education
Resources for learning Python
● Official Python Documentation:
https://docs.python.org/2/
● Think Python:
http://www.greenteapress.com/thinkpython/thinkpython.html
● Stack Overflow (Q&A):
http://stackoverflow.com
● Automate the boring stuff.
https://automatetheboringstuff.com and https://www.udemy.com/automate/
● Learn Python the hard way:
http://learnpythonthehardway.org/book/
● Google’s Python Class
https://developers.google.com/edu/python/?hl=en
Enabling Knowledge Leaders
Impacting Education
Data Types
● Basic Data Types
○ int → e.g. >>>3
○ float → e.g. >>>3.0
○ string → e.g. >>>‘Hello’, >>>“Hello”
○ boolean → e.g. >>>True , >>>False
○ NoneType → e.g. >>>None
● Complex Data Types (Will be discussed later)
○ tuple
○ list
○ dictionary
● Type command-> >>>type(3) returns int
Enabling Knowledge Leaders
Impacting Education
Expressions
● Try these out in the python interpreter
● Addition, subtraction >>>1 + 2 , >>>3.0 + 4
● Multiplication >>>3*4, >>>5*2.0
● Division >>>3/2, >>>3.0/2, >>>3/2.0
● Forced integer division 3.0 // 2
● Modulus >>>12 % 7, >>>20 % 8.5
● Comparison operators ==, !=, >, >=, <, <=
● Logical operators and, or, not
● Exponent operators >>>3 ** 7
Enabling Knowledge Leaders
Impacting Education
Expressions
● Membership & Identity Operators in, not in, is, is not
Assume a = ‘Vasu’, b = ‘V’
>> b in a, b not in a, a is b, a is not b
● Assignment Operators +=, -=, *=, /=, //=, **=, %=
Assume a = ‘4’
>> a +=2 (a = a + 2 )
>> a -=2 (a = a - 2 )
>> a *=2 (a = a * 2 )
>> a /=2 (a = a / 2 )
>> a //=2 (a = a // 2 )
>> a **=2 (a = a ** 2 )
>> a %=2 (a = a % 2 )
10
Enabling Knowledge Leaders
Impacting Education
Variables and Assignment
● Values can be stored in variables. Variable names must start with
a letter or _ and must not be a reserved word
● String concatenation:
Value of c+d?
Value of c+d+e*3?
Value of c / d
+ and * are ‘overloaded’ operators
11
Enabling Knowledge Leaders
Impacting Education
Branching (if, elif, else)
● Used to make decisions
● Elif and else are optional
● Syntax:
12
Enabling Knowledge Leaders
Impacting Education
Taking input from user & displaying output
● >>>a = input(“Enter a Sentence”)
● The python prompt will allow the user to enter an input and
will bind a to the input provided.
● Input is stored as a string.
● String slicing
● a = “Hello PSSD Team”
a[1:5]
a[:-2]
a[3:]
● Printing output: >>>print(<expression>)
13
Enabling Knowledge Leaders
Impacting Education
Data Type Conversion
● Data of one type may be converted to another type if
the value is valid in the destination type.
● a = “123”
● b = int(a)
● c = float(a)
● d = 256
● e = str(256)
● f = int(27f) #throws an error
14
Enabling Knowledge Leaders
Impacting Education
Iteration
● while loop
● Syntax:
● Condition is evaluated every time we enter the loop
● break can stop execution of the while loop if
required (Generally used inside an if)
15
Enabling Knowledge Leaders
Impacting Education
Iteration contd…
● for loop
● Syntax:
● item is automatically assigned and incremented in
each iteration. An example:
● Range function: >>>range (a,b,c)
16
Enabling Knowledge Leaders
Impacting Education
QA
17
Enabling Knowledge Leaders
Impacting Education
Python Modules – Module 2
Introduction to Python
18
Enabling Knowledge Leaders
Impacting Education
Outline/Agenda
● Functions & Abstraction- Purpose, Defining, Calling
● Arguments & Default Values
● Scope of Variables
● Function Design Recipe & Docstrings
● Square Root Examples -> Enumeration & Bisection
● Recursion
● Methods
● Accessing modules
● Files - Reading from, Writing to & Closing
19
Enabling Knowledge Leaders
Impacting Education
Functions
● A sequence of statements that performs some
computation
● May have inputs and outputs
○ e.g. >>>type(3)
● type is a function which takes an object as input(in
this case the number 3) and returns the object type
as output(in this case type int)
20
Enabling Knowledge Leaders
Impacting Education
Why functions
● Makes code smaller & readable
● Can perform a task without worrying about actual
implementation
● Specific tasks can be developed, tested and
debugged independently
● Statements of code can be reused
● A change in the implementation(e.g. changing to a
more efficient algorithm) needs to be done in only
one place
21
Enabling Knowledge Leaders
Impacting Education
How to define & call a function
● The syntax to define a function is as follows:
● Here a function myFunction is defined. It takes 2 arguments as
inputs and returns a value.
We can call the function like this:
● The function is called; arg1 is bound to input1, arg2 is bound to
input2. The statements in the function body are executed and the
expression after the return statement is evaluated and returned as
the output of the function that is bound to a
22
Enabling Knowledge Leaders
Impacting Education
Making arguments optional
● Function parameters can be given default values in
the function definition. By doing this, you can make
passing the argument to the function optional. The
argument is not passed, the default value is used.
23
Enabling Knowledge Leaders
Impacting Education
Scope of variables
● The scope of parameters and variables of a function
is limited to the function.
24
Enabling Knowledge Leaders
Impacting Education
Function Design Recipe & Docstrings
● Follow the following recipe while creating a function to perform a
task:
○ Examples
○ Type Contract
○ Header
○ Description
○ Body
○ Test
● Following this recipe will make it easy to write your functions and
also easy for someone to reuse them
● A function’s Docstring is a multi line string using 3 double or single
quotes. It contains Type Contract, Description, & Examples
25
Enabling Knowledge Leaders
Impacting Education
Function Design Recipe & Docstrings
26
Enabling Knowledge Leaders
Impacting Education
Example of Square Root – Exhaustive
Enumeration
def mysquareroot(num):
epsilon = 0.01 # accuracy param
step = epsilon**2
numGuesses = 0
ans = 0
while abs(ans**2 – num) >= epsilon and ans <=x:
ans += step
numGuesses +=1
print ‘Number of iterations’, numGuesses
if abs(ans**2 – num) < epsilon:
return ans
else:
return None #Failed to find a squareroot
27
Enabling Knowledge Leaders
Impacting Education
Example of Square Root - Bisection
def mysquareroot(num):
epsilon = 0.01
lower = 0.0
upper = num
ans = (upper + lower)/2.0
numGuesses = 1
while True:
numGuesses +=1
if abs(ans**2-num) < epsilon: # ans is an accurate enough square root
print "number of iterations: ", numGuesses
return ans
elif ans**2 > num: #ans is larger than the required square root
upper = ans
ans = (upper + lower) / 2
else: #ans is smaller than the required square root
lower = ans
ans = (upper + lower) / 2
28
Enabling Knowledge Leaders
Impacting Education
Recursion
● In programming, recursion means a function calling
itself.
● Recursive thinking is to break a problem into a
simpler problem of itself plus some simple
operations.
● For a recursive call to terminate, there needs to be
at least one base case.
29
Enabling Knowledge Leaders
Impacting Education
Recursion example
● Consider the code:
● What happens when I call the function fact?
● Lets visualize it! http://www.pythontutor.com
30
Enabling Knowledge Leaders
Impacting Education
Methods
● Methods are nothing but functions defined for specific object types
● The way they are called is
○ <object>.method(<arg2>, <arg3>, …)
● For example, string objects have a method called find. It takes a substring
as argument and returns the first index where it is found in a string.
Returns -1 if not found:
● You can pass a second argument(integer) to search for the substring from
a particular index of the string onward(check the python documentation:
https://docs.python.org/2/library/string.html)
31
Enabling Knowledge Leaders
Impacting Education
Accessing modules
● Python has many modules developed by other
people which we can reuse.
● To import a module that has been installed, use the
import statement followed by the module name
● when using a variable, function or method from the
module, use <module>.<function/variable>
32
Enabling Knowledge Leaders
Impacting Education
Files- Writing
● First create a file object(file handle) using the open
command. Parameters are filename and mode. For
writing, mode is ‘w’. (use ‘a’ for append mode)
● Write text using the write method. No newline
33
Enabling Knowledge Leaders
Impacting Education
Files- Reading
● First create a file object(filehandle) using the open command.
Parameters are filename and mode. For writing, mode is ‘r’.
● Many ways to read. The simplest is to use a for loop.
● You can also use the method readline() to get one line at a
time(including the “\n” character. (use <string>.strip to get rid of the
newline character) )
● Use seek(0) to move the file handle to the beginning of the file.
34
Enabling Knowledge Leaders
Impacting Education
Files- Closing
After reading or writing from/to a file, you must close
the file.
● Use <fileobject>.close()
● Without closing the file, the data may not be saved
properly.
35
Enabling Knowledge Leaders
Impacting Education
QA
36
Enabling Knowledge Leaders
Impacting Education
Python Modules – Module 3
Introduction to Python
37
Enabling Knowledge Leaders
Impacting Education
Outline/Agenda
○ Tuples
○ Lists
○ Dictionaries
○ Some common useful methods
○ Assertions & Exceptions
○ Regular Expressions
○ Miscellaneous useful functions
38
Enabling Knowledge Leaders
Impacting Education
Tuples
● Tuples are more generalized version of strings. A tuple is an
ordered sequence of objects(that can be any type)
● They can be created using comma separated objects inside
parenthesis
>>> a = (1, 2, ‘cat’)
● Tuples are immutable:
>>> a[1] = 0 # This would give an error
● A single value tuple is created with a comma to differentiate it from
just being a number in parenthesis:
>>> b = (1,) # since b = (1) is just a more verbose b = 1
● Like strings, tuples can be concatenated(t1+t2), indexed(t1[i]) and
sliced(t1[i:j:k]).
39
Enabling Knowledge Leaders
Impacting Education
Tuples (cont.)
● Can be used for multiple assignment
● Because of tuples, you can swap variables in python like this:
● >>> a, b = b, a
● They can be used to return multiple values from functions. (a tuple is implicitly
created without having to use parenthesis)
return a, b
● Since tuples are objects, tuples can contain other tuples:
● >> t1 = ((1, ‘two’, 3), 3.25)
● >>> len(t1) #this returns the number of elements in outermost tuple
2
40
Enabling Knowledge Leaders
Impacting Education
Tuples Example
● A program to find the common divisors of 2 numbers
41
Enabling Knowledge Leaders
Impacting Education
Lists
● Lists are dynamic arrays in python. They are created using square
brackets []. Elements are comma separated.
○ >>> a = [“name”, “age”, “address”]
● Lists can contain a mixture of data types
○ >>> b = [“Buck”, [5, 12], 3.3, (‘cat’, ‘dog’)]
● They are mutable and an element can be changed in place
○ >>>a[1] = “number” # this works unlike in tuples and in strings
● Their size can be changed (append, pop and other methods)
● You can get the number of elements using len(<list>)
● You can access an element using its index a[0]
● You can get part of a list using slicing similar to strings a[0:2]
● You can concatenate two lists a + b
42
Enabling Knowledge Leaders
Impacting Education
Lists – Examples of Operations
43
Enabling Knowledge Leaders
Impacting Education
Lists - Common Methods
● list.append(elem) -- adds a single element to the end of the list. Common error: does not
return the new list, just modifies the original.
● list.insert(index, elem) -- inserts the element at the given index, shifting elements to the
right.
● list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is
similar to using extend().
● list.index(elem) -- searches for the given element from the start of the list and returns its
index. Throws a ValueError if the element does not appear (use "in" to check without a
ValueError).
● list.remove(elem) -- searches for the first instance of the given element and removes it
(throws ValueError if not present)
● list.sort() -- sorts the list in place (does not return it). (The sorted() function shown below is
preferred.)
● list.reverse() -- reverses the list in place (does not return it)
● list.pop(index) -- removes and returns the element at the given index. Returns the rightmost
element if index is omitted (roughly the opposite of append()).
44
Enabling Knowledge Leaders
Impacting Education
Lists - Extras
● Aliasing(consequence of mutability):
○ >>>PSSD= [‘Power’, ‘WEBENCH’]
○ >>>SYSTEM_ISS = PSSD
○ >>>SYSTEM_ISS.append(‘LDO’)
○ >>> PSSD # What is the value of PSSD?
● List Comprehensions:
○ A simple way to generate lists that follow a pattern
○ >>> a = [x**2 for x in range(1, 10)]
Creates a list [1, 4, 9, 16, 25, 36, 49, 64, 81]
○ You can add conditions as well:
○ >>> b = [x**2 for x in range(1,10) if x % 2 == 0]
Creates a list [4, 16, 36, 64]
● Dumping file contents into a list:
○ mylist = fileobj.readlines()
45
Enabling Knowledge Leaders
Impacting Education
Lists - Cloning
● Avoid mutating a list over which you are iterating:
● Instead, use a clone of the list using L1[:]
46
Enabling Knowledge Leaders
Impacting Education
Dictionaries
● Dictionaries are like lists but are more general.
● In case of lists, the indices are integers from 0..n
● In case of dictionaries, the indices can be any non-mutable
object(int/float/string/tuple)
● Lookup is super-fast and is almost independent of the length
of the dictionary
● A dictionary can be created using braces. Passing a
key-value pair while creating is optional:
● >>>a = {} or >>>a={key:value}
● Key-value pairs can be added(dicts are mutable):
● >>> a[key] = value
47
Enabling Knowledge Leaders
Impacting Education
Dictionaries
● By default a for loop iterates over keys(returned in random
order).
○ >>> for key in dict:
● We can also explicitly mention it for readability:
○ >>>for key in dict.keys():
● We can also iterate over values:
○ >>>for value in dict.values():
● The for loop can also iterate over key-value pairs in tuple form:
○ >>>for (key, value) in dict.items():
● We can delete an entry from the dictionary using del:
○ >>>del dict[key]
48
Enabling Knowledge Leaders
Impacting Education
Dictionary example
49
Enabling Knowledge Leaders
Impacting Education
Some Common Useful Methods
● >>>a = <string>.split(<delimiter>) #returns a lists obtained by
splitting a string at delimiter
● >>>c = <delimiter>.join(<list>) # returns a strings formed by joining
elements of the list using the delimiter between elements
● >>>b = <string>.find(“<substring>”) #returns index at which first
element of substring is found in string. returns -1 if not found
● >>> c = <string>.upper() ; >> d = <string>.lower() #change case
● >>> e = <string>.replace(<old>, <new>) #returns strings with all
occurrences of old replaced by new
● >>> f = <string>.strip() # removes whitespace characters from the
beginning and end
● >>> g in <sequence> # returns True if a exists in the sequence,
False otherwise
50
Enabling Knowledge Leaders
Impacting Education
Assertions
● Assertions are checks to make sure the program will function properly.
● Syntax:
○ assert <condition>, <message>
● Normally the condition should be True. If False, the program stops executing
and raises an AssertionError
● Useful to prevent a program from giving erroneous output
● For example, in fact function defined previously, we can make sure the user
passes an int as an argument:
51
Enabling Knowledge Leaders
Impacting Education
Exceptions
● An exception is a run time error. When it occurs, the program
halts and execution is passed to the error handling code if it
exists.
● Examples of causes of exceptions: trying to use a variable that
wasn’t defined(NameError), going out of index bound in a
list/string(IndexError), opening a file for reading which does not
exist(IOError).
● We can handle exceptions using a try-except block. e.g.
52
Enabling Knowledge Leaders
Impacting Education
Regular Expressions
● Regular expressions are a powerful language for matching text patterns
● Import regex module using: import re
● Typical usage: >>>match = re.search(pat, str)
● Returns a match object if found, else None. Use the group method on the match object:
● raw strings: always use raw strings with regex, to prevent python from processing them
in any other unintended manner. to make a string raw: r”<string>”
● Please read the comprehensive documentation here:
https://docs.python.org/2/library/re.html or refer to
https://developers.google.com/edu/python/regular-expressions for the most commonly used
regex
53
Enabling Knowledge Leaders
Impacting Education
Regular Expressions Quick Guide
● ^ Matches the beginning of a line
● $ Matches the end of the line
● . Matches any character
● \s Matches whitespace
● \S Matches any non-whitespace character
● * Repeats a character zero or more times
● *? Repeats a character zero or more times (non-greedy)
● + Repeats a character one or more times
● +? Repeats a character one or more times (non-greedy)
● [aeiou] Matches a single character in the listed set
● [^XYZ] Matches a single character not in the listed set
● [a-z0-9] The set of characters can include a range
● ( Indicates where string extraction is to start
● ) Indicates where string extraction is to end
● \ Escape character, to make a special character behave normally
54
Enabling Knowledge Leaders
Impacting Education
Regular Expressions
● findall function
○ finds *all* the matches and returns them as a list of strings, with each string representing
one match
○ If the pattern includes 2 or more parenthesis groups, then instead of returning a list of
strings, findall() returns a list of tuples
● options: re.<option> as additional argument to search/findall
IGNORECASE -- ignore upper/lowercase differences for matching, so 'a' matches both 'a' and 'A'.
DOTALL -- allow dot (.) to match newline -- normally it matches anything but newline. This can trip you up -- you think .*
matches everything, but by default it does not go past the end of a line. Note that \s (whitespace) includes newlines, so if
you want to match a run of whitespace that may include a newline, you can just use \s*
MULTILINE -- Within a string made of many lines, allow ^ and $ to match the start and end of each line. Normally ^/$ would
just match the start and end of the whole string.
● substitution
○ re.sub(pat, replacement, str)
○ use \1, etc to use matched content in the substitution(similar to notepad++). This is
equivalent to $1 in Perl
55
Enabling Knowledge Leaders
Impacting Education
Miscellaneous useful functions
Make sure you import the required module to use these
● os.listdir(<directory>) – returns a list of files in directory
● os.getcwd() – returns current working directory
● os.chdir(<directory>) – change the current working directory
● os.system(<command>) – runs a system command
● os.rename(<src>, <dest>) – renames a file/dir from src to dst
● subprocess.call(<program>, <arg>) opens the program. args are
optional
● time.sleep(<seconds>)- suspends execution for given seconds
● webbrowser.open(<url>)- opens the given url in default browser
● Refer to https://docs.python.org/2/library/index.html for all standard
library modules & functions and their details
● Alternatively, google search for what you want to do.
56
Enabling Knowledge Leaders
Impacting Education
Bonus: A Sneak Peek at pylab
● pylab can be used to plot graphs
● You need to provide x and y values, ideally each being lists
of numbers (lists must have the same length)
● Other useful functions:
● pylab.xlabel(<label as str>); pylab.ylabel(<label as str>)
● pylab.savefig(<filename as str>)
● pylab.close() #this is important to save memory when processing many figures
● http://matplotlib.org/users/pyplot_tutorial.html
● mathplotlib.pyplot is similar to pylab(same commands AFAIK)
57
Enabling Knowledge Leaders
Impacting Education
QA
58
Enabling Knowledge Leaders
Impacting Education
THANK YOU
59
Enabling Knowledge Leaders