Python Programming
Python Programming
Python Programming
Introduction to Python
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)
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
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
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
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
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
11
12
13
14
Iteration
● while loop
● Syntax:
15
Iteration contd…
● for loop
● Syntax:
16
QA
17
Introduction to Python
18
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
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
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
22
23
Scope of variables
● The scope of parameters and variables of a function
is limited to the function.
24
○ 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
26
27
28
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
Recursion example
● Consider the code:
30
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
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
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
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
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
QA
36
Introduction to Python
37
Outline/Agenda
○ Tuples
○ Lists
○ Dictionaries
○ Some common useful methods
○ Assertions & Exceptions
○ Regular Expressions
○ Miscellaneous useful functions
38
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
Tuples (cont.)
● Can be used for multiple assignment
40
Tuples Example
● A program to find the common divisors of 2 numbers
41
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
43
44
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
Lists - Cloning
● Avoid mutating a list over which you are iterating:
46
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
Dictionaries
● By default a for loop iterates over keys(returned in random
order).
○ >>> for key in dict:
48
Dictionary example
49
50
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
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
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
54
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
● 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
56
57
QA
58
THANK YOU
59