Weeks 4 To 7
Weeks 4 To 7
Structure
• 10 Weeks of Python (Starting 4th week till 13th week)
• Python:
• 4 take home weekly assignments best 3 to be taken (27%)
• 22nd Sep,
• 6th Oct,
• 20th Oct,
• 3rd Nov
• 2 in-class coding tests (18%)
• 25th Oct
• 15th Nov
• Final project (25%)
• Given on 17th Nov, to be submitted by 1st Dec
Weeks 4 to 7
Why Python?
• Why do you want to learn Python/programming?
• What would you use Python for?
Why Python?
Python History
Source: https://bootcamp.berkeley.edu/blog/most-in-demand-
programming-languages/
Python Today
• A large and active scientific computing and data analysis community
• Now one of the most important languages for
• Data science, Machine learning, Deep Learning (rapid prototyping)
• Towards Enterprise Application Development
• Packages: NumPy, pandas, matplotlib, SciPy, scikit-learn, statsmodels,
etc.
What is python?
• Object oriented language
• Interpreted language
• (Initial Source code, Intermediate Byte Code, Execution
in Virtual Machine)
• Supports dynamic data type
• Independent from platforms
• Focused on development time
• Simple and easy grammar
• Automatic memory management
• It’s free (open source)!
Python Syntax
• Much of it is similar to C syntax
• Exceptions:
• missing operators: ++, --
• no curly brackets,{}, for blocks; uses whitespace
• different keywords
• lots of extra features
• no type declarations!
Modes of Use
1. Ipython / Jupyter Notebook
Python can be run interactively
Used extensively in research
2. Other IDEs
PyCharm
Jupyter Notebook
Stop
Save Cut, copy execution Block type
paste
New block Move block Reset block
And clear output
Kernel/Restart & Clear output
Running blocks
• By pressing the Run button
• Shift + Enter – runs block
• Alt + Enter – creates a new block
Commenting
• Useful when your code needs further explanation. Either for your
future self and anybody else.
• Useful when you want to remove the code from execution but not
permanently
• Comments in Python are done with #
Variables and Operators
Python as a calculator
• Distance between Edinburgh and London is 403 miles.
• Let us calculate the distance between Edinburgh and London in km
Why We Need Variables?
• Great calculator but how can we make it store values?
• Yes by defining variables
• Can later be called by the variable name
• Variable names are case sensitive and unique
Why We Need Variables?
We can now reuse the variable mileToKm in the next block without
having to define it again!
Type of Variables
• Python is both a strongly typed and a dynamically typed language.
• Strong typing means that variables do have a type and that the type matters when
performing operations on a variable.
• Dynamic typing means that the type of the variable is determined only during runtime.
• Due to strong typing, types need to be compatible with respect to the operand when
performing operations. For example Python allows one to add an integer and a floating
point number, but adding an integer to a string produces error.
• friendly = 1
if (friendly):
greeting = "hello world"
else:
greeting = 12**2
print (greeting)
• Everything is a variable:
• functions, modules, classes
Variable Naming Rules
• Names are case sensitive and cannot start with a number. They can
contain letters, numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
You can find the type of a variable using type(). For example type type(x).
Casting Variable Types
Python offers us a way of converting variables to different types!
Casting is the operation of converting a variable to a different type
https://techvidvan.com/tutorials/python-operator-precedence/
Order precedence example
(16 ** 2) / 4
Comparison operators
• I.e. comparison operators
• Return Boolean values
(i.e. True or False)
• Used extensively for
conditional statements
Comparison examples
False
Logical operators
True True
Another example
vs
Quiz
vs
13 49
Sequences or Ordered Data Structures:
Tuples, Strings, and Lists
Sequence Types
1. Tuple: (‘john’, 32, [‘APU’])
· A simple immutable ordered sequence of
items
· Items can be of mixed types, including
collection types
2. Strings: “John Smith”
• Immutable
• Conceptually very much like a tuple
3. List: [1, 2, ‘john’, (‘up’, ‘down’)]
· Mutable ordered sequence of items of mixed
types
Similar Syntax
• All three sequence types (tuples, strings, and lists) share
much of the same syntax and functionality.
• Key difference:
• Tuples and strings are immutable
• Lists are mutable
• The operations shown in this section can be applied to all
sequence types
• most examples will just show the operation performed on
one
Sequence Types 1
• Define tuples using parentheses and commas
>>> tu = (23, ‘abc’, 4.56, (2,3),
‘def’)
• Define lists are using square brackets and commas
>>> li = [“abc”, 34, 4.34, 23]
• Define strings using quotes (“, ‘, or “““).
>>> st = “Hello World”
>>> st = ‘Hello World’
>>> st = “““This is a multi-line
string that uses triple quotes.”””
Sequence Types 2
• Access individual members of a tuple, list, or string
using square bracket “array” notation
• Note that all are 0 based…
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> tu[1] # Second item in the tuple.
‘abc’
• Be careful: the in keyword is also used in the syntax of for loops and list
comprehensions
The + Operator
The + operator produces a new tuple, list, or string whose value is the concatenation of
its arguments.
• The * operator produces a new tuple, list, or string that “repeats” the
original content.
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> “Hello” * 3
‘HelloHelloHello’
Tuples
• What is a tuple?
• A tuple is an ordered collection which cannot
be modified once it has been created.
• In other words, it's a special array, a read-only array.
• How to make a tuple? In round brackets
• E.g.,
>>> t = ()
>>> t = (1, 2, 3)
>>> t = (1, )
>>> t = 1,
>>> a = (1, 2, 3, 4, 5)
>>> print a[1] # 2
Tuples
• Effectively lists that are immutable (I.e. can't be changed)
Tuples
• The comma is the tuple creation operator, not parens
>>> 1,
(1,)
These are called methods and add extra functionality to the String.
If you want to see more methods that can be applied to a string simply
type in dir('str')
Strings and formatting
i = 10
d = 3.1415926
s = "I am a string!"
print ("%d\t%f\t%s" % (i, d, s))
print (“newline\n“)
print ("no newline“)
Mixing up strings and numbers
Often we would need to mix up numbers and strings.
It is best to keep numbers as numbers (i.e. int or float)
and cast them to strings whenever we need them as a string.
Multiline strings
Strings
• "hello"+"world" "helloworld" # concatenation
• "hello"*3 "hellohellohello" # repetition
• "hello"[0] "h" # indexing
• "hello"[-1] "o" # (from end)
• "hello"[1:4] "ell" # slicing
• len("hello") 5 # size
• "hello" < "jello" 1 # comparison
• "e" in "hello" 1 # search
• New line: "escapes: \n "
• Line continuation: triple quotes ’’’
• Quotes: ‘single quotes’, "raw strings"
Quiz
Do you see anything wrong with this block?
Another more generic way to fix it
len(x)
List: A Compound Data Type
• List:
• A container that holds a number of other objects, in a
given order
• Defined in square brackets
a = [1, 2, 3, 4, 5]
print a[1] # number 2
some_list = []
some_list.append("foo")
some_list.append(12)
print len(some_list) # 2
List
• a = [99, "bottles of beer", ["on", "the", "wall"]]
• Flexible arrays, not Lisp-like linked lists
• Same operators as for strings
• a+b, a*3, a[0], a[-1], a[1:], len(a)
• Item and slice assignment
• a[0] = 98
• a[1:2] = ["bottles", "of", "beer"]
• a now is [98, "bottles", "of", "beer", ["on", "the", "wall"]]
• del a[-1]
• a now is [98, "bottles", "of", "beer"]
List
• One of the most useful concepts
• Group multiple variables together (a kind of container!)
Indexing a list
• Indexing – accessing items within a data structure
Advanced Programming
16 Mar 2025
Spring 2002
List comprehensions
• cross products:
>>> vec1 = [2,4,6]
>>> vec2 = [4,3,-9]
>>> [x*y for x in vec1 for y in vec2]
[8,6,-18, 16,12,-36, 24,18,-54]
>>> [x+y for x in vec1 and y in vec2]
[6,5,-7,8,7,-5,10,9,-3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8,12,-54]
Advanced Programming
16 Mar 2025
Spring 2002
List comprehensions
• can also use if:
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]
Advanced Programming
16 Mar 2025
Spring 2002
del – removing list items
• remove by index, not value
• remove slices from list (rather than by assigning an empty list)
>>> a = [-1,1,66.6,333,333,1234.5]
>>> del a[0]
>>> a
[1,66.6,333,333,1234.5]
>>> del a[2:4]
>>> a
[1,66.6,1234.5]
Advanced Programming
16 Mar 2025
Spring 2002
Mutability:
Tuples vs. Lists
List vs. Tuple
• What are common characteristics?
• Both store arbitrary data objects
• Both are of sequence data type
• What are differences?
• Tuple doesn’t allow modification
• Tuple doesn’t have methods
• Tuple supports format strings
• Tuple supports variable length parameter in function call.
• Tuples slightly faster
Summary: Tuples vs. Lists
• Lists slower but more powerful than tuples
• Lists can be modified, and they have lots of handy operations and
methods
• Tuples are immutable and have fewer features
• To convert between tuples and lists use the list() and tuple()
functions:
li = list(tu)
tu = tuple(li)
Mutability
Mutable object – can be changed after creation.
• Potentially confusing:
• extend takes a list as an argument.
• append takes a singleton as an argument.
>>> li.append([10, 11, 12])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [10, 11, 12]]
Data Type Wrap Up
• Lists, Tuples, and Dictionaries can store any type (including other lists,
tuples, and dictionaries!)
• Only lists and dictionaries are mutable
• All variables are references
Quiz
• Which one is mutable: List or Tuple?
Dictionaries
• Dictionaries: curly brackets
• What is dictionary?
• Refer value through key; “associative arrays”
• Like an array indexed by a string
• An unordered set of key: value pairs
• Values of any type; keys of almost any type
• {"name":"Guido", "age":43, ("hello","world"):1,
42:"yes", "flag": ["red","white","blue"]}
d = { "foo" : 1, "bar" : 2 }
print d["bar"] # 2
some_dict = {}
some_dict["foo"] = "yow!"
print some_dict.keys() # ["foo"]
Methods in Dictionary
• keys()
• values()
• items()
• has_key(key)
• clear()
• copy()
• get(key[,x])
• setdefault(key[,x])
• update(D)
• popitem()
Dictionary details
• Keys must be immutable:
• numbers, strings, tuples of immutables
• these cannot be changed after creation
• reason is hashing (fast lookup technique)
• not lists or other dictionaries
• these types of objects can be changed "in place"
• no restrictions on values
• Keys will be listed in arbitrary order
• again, because of hashing
Dictionaries
• Similar to actual dictionaries
• They are effectively 2 lists
combined – keys and values
• We use the keys to access the
values instead of indexing them
like a list
• Each value is mapped to a
unique key
Dictionary definition
Defined as comma separated key : value pairs:
Comma separated
Curly brackets
Dictionary properties
• Each value is mapped to an unique key
• Values are accessed by their key
• Key are unique and are immutable
• Values cannot exist without a key
Dictionaries
Let us define the one from the previous image
Accessing a dictionary
Values are accessed by their keys (just like a dictionary)
Conditional statement
Executed if answer is True
• elif = else + if which means that the previous statements must be false
for the current one to evaluate to true
Bitcoin broker example
Quiz
• What would happen if both conditions are True?
Control flow
• if, if/else, if/elif/else
if a == 0:
print "zero!"
elif a < 0:
print "negative!"
else:
print "positive!"
Notes:
• blocks delimited by indentation!
• colon (:) used at end of lines containing control flow keywords
Loops
For loop
• Allows us to iterate over a set amount of variables within a data
structure. During that we can manipulate each item however we want
• What if we have much more than 4 items in the list, say, 1000?
For example
• Now with a for loop
• while loops
a = 10
while a > 0:
print a
a -= 1
Control flow
• for loops
for a in range(10):
print a
Control flow
a = [3, 1, 4, 1, 5, 9]
for i in range(len(a)):
print a[i]
Control flow
• Common while loop idiom:
f = open(filename, "r")
while True:
line = f.readline()
if not line:
break
# do something with line
Control flow: odds & ends
def foo(x):
y = 10 * x + 2
return y
f = make_incrementor(42)
f(0)
f(1)
Advanced Programming
16 Mar 2025
Spring 2002
Exception Handling
• The build-in exceptions in Python are raised when the program
encounters an error.
• When exception occur, the Python interpreter stops executing
the current process and passes the control it the calling process
until it is handled.
• If not handled, the program will crash.
• Some common exceptions are:
• ZeroDivisionError: Occurs when a number is divided by zero.
• NameError: It occurs when a name is not found. It may be local or global.
• IndentationError: If incorrect indentation is given.
• IOError: It occurs when Input Output operation fails.
• EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.
Exception Handling
try :
Try running this code
except:
Run this only if exception occurs
finally:
Always run this
Catching Exceptions
#python code a.py
x = 0
try:
print 1/x
except ZeroDivisionError, message:
print "Can’t divide by zero:"
print message
>>>python a.py
Can't divide by zero:
integer division or modulo by zero
Write a program which asks for 2 numbers and
handles exception when a number is divided by
zero
Pseudocode:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
print("a/b = ",a/b)
except ZeroDivisionError:
print(“This is inside except block”)
print("The value of b can't be 0")
finally:
print(“this is inside finally block and always
executed”)
Modules
Why use modules?
• Code reuse
• Routines can be called multiple times within a program
• Routines can be used from multiple programs
• Namespace partitioning
• Group data together with functions used for that data
• Implementing shared services or data
• Can provide global data structure that is accessed by
multiple subprograms
Modules
• Modules are functions and variables defined in separate files
• Items are imported using from or import
• from module import function
• function()
• import module
• module.function()
• Modules are namespaces
• Can be used to organize variable names, e.g.
• atom.position = atom.position - molecule.position
Modules
• Access other code by importing modules
import math
print math.sqrt(2.0)
• or:
from math import sqrt
print sqrt(2.0)
Modules
• or:
from math import *
print sqrt(2.0)