MA422 Numerical Analysis: Week 3 Lecture 1
Loops, Functions, Classes, and intro to Objects
Jawwad Chattha
March 6, 2023
Python code
total = 0
for i in range(100):
# the first code line indented begins code block
total = total + i
# when the indentation ends, so does the code block
• Statements clearly begin with a : in Python
• Python forces you to indent your code blocks – this makes Python
highly readable
• You don’t need end statements in Python, instead you end the
indentation block
1
While loop
i = 0
while i < 10:
print(i)
i += 1 # this takes the previous i value and adds 1 to it
print('The while loop has finished')
Notice how the format is just like a if statment. Using the : to begin the
code block. The code block is indicated by the indentation. There are no
end statements in Python. Rather code blocks end when the indentation
is returned to normal.
2
Iterating over a list
x = [0,1,2,3,4,5,6]
for i in x:
print(i)
3
Iterating over two lists
This code simultaneously iterates over both lists
x = [0,1,2,3,4,5,6]
y = [7,8,9,10,11,12,13]
for xVal, yVal in zip(x,y):
print(xVal, yVal)
4
Iterating over two lists - using range
This code simultaneously iterates over both lists. len() tells us the length
of a list.
x = [0,1,2,3,4,5,6]
y = [7,8,9,10,11,12,13]
for i in range(len(x)):
print(x[i], y[i])
5
For loop - Iterating with range()
total = 0
for i in range(100):
# the first code line indented begins code block
total = total + i
How range() works.
• for i in range(100): - iterates from 0 to 99 (100 times)
• range(0,100) - iterates from 0 to 99 (100 times)
• range(0,100,2) - iterates 0, 2, 4, ..., 98 (50 times)
• range(startPoint, endPoint, stepSize) where startPoint is inclusive,
endPoint is exclusive
6
For loop range(0,9)
for i in range(0,9):
'''
this is a for loop,
that will print 0, 1, 2, 3, 4, 5, 6, 7, 8
'''
print(i)
These are the most basic for loop. Again the : initiates the code block,
and the indentation indicates the beginning and end of a code block.
7
Nesting a for loop
Remember your code block is denoted with indentation in Python.
for i in range(-10,11):
if i < 0:
print(i, 'is negative')
elif i > 0:
print(i, 'is positive')
else:
print(i, 'is zero')
This will loop for i = -10, -9, ..., 10. Then an if-else statement is used to
print whether i is negative, positive,or zero.
8
Use break to break loop
for i in range(-10,11):
if i == 0:
break
print(i)
i = 0
n = 0
while i == 0:
n += 1
if n > 100:
break
9
Double nest loops
You can double nest loops like this.
for i in range(0,10):
for j in range(0,10):
print(i,j)
• Use functions with specific tasks to avoid a large number of nested
layers
• It is really hard to debug heavily layered code- but easy to test
functions
• Your break placement in nested code matters. Which loop are you
trying to break???
10
Loops with the index and value - enumerate
Often I need to create a loop through an array, where I’ll need the index
and value. I use enumerate() to do this.
x = [8,181,129,10,'hi']
for index, value in enumerate(x):
# index refers to the index on the list x
# value is the current value of x the loop is on
print(index, value)
11
Loops with the index and value - enumerate
If it isn’t clear, index and value can be named whatever you want.
x = [8,181,129,10,'hi']
for i,j in enumerate(x):
print(i,j)
12
List comprehension - basics
This is one really neat feature in Python where you can run loops and if
statements while generating a list.
List comprehension creates many Pythonic code one liners.
An interested read [Link]
python-list-comprehensions-now-in-color/
x = [0,1,2,3,4,5]
y = [i**2 for i in x]
# y is a list where each item in x is squared
13
List comprehension - more advanced
x = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
y = [i for i in x if abs(i) < 3]
# y is a list containing each item in x
# such that the absolute value of each item in x is less than 3
x = [0,1,2,3,4,5]
y = [i**2 for i in x if i%2 ==0]
# y is a list where each item in x is squared
# if the item in x is an even number
x = [0,1,2,3,4,5]
y = [i**2 for i in x if i**2%2 == 0]
# y is a list where each item in x is squared
# if the item squared is an even number
14
list comprehension - multiple loops
in : [[i,j] for i in range(2) for j in range(2)]
out: [[0, 0], [0, 1], [1, 0], [1, 1]]
in : # this is a triple nested for loop creating a list!
[[i,j,k] for i in range(2) for j in range(2) for k in range(2)]
out: [[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]]
15
Functions - some basics
Functions are simple in Python.
Let’s create a simple hello world function.
def helloWorld():
print('Hello world function :-)')
Let’s create a function to take the cube root of a number.
def cubeRoot(x):
return x**(1.0/3.0)
• The def statement is used to define a function.
• The name of the function here is cubeRoot.
• Functions used () to pass input.
• Input for cubeRoot is x.
• Input is optional, see helloWorld().
• Again the : is used at the end of the statement.
• Indentation denotes the code block of the function.
16
Functions - optional arguments and input - output
def myRoot(x,c=3.0):
'''
myRoot(x) returns the cube root of x by default
myRoot(x,c) returns the c root of x
'''
return x**(1.0/c)
• c is an optional argument, that we set to 3 on default
• return is used to pass output
• x is the input
• in general the input can be anything, objects, lists, strings, floats,
etc.
• the output can also be anything, objects, lists, strings, floats, etc
17
Functions - multiple returns
def rootz(x):
'''
a,b,c,d = rootz(x) for some float or integer x
a = square root of x; b = cube root of x
c = x**0.25; d = x**0.2
'''
return x**0.5, x**(1.0/3.0), x**0.25, x**0.2
in : y = rootz(4.0)
print(y)
out: (2.0, 1.5874010519681994, 1.4142135623730951, 1.31950791077
in : i,j,k,l = rootz(99.0)
print(i,j,k,l)
out: 9.9498743710662 4.626065009182741 3.1543421455299043 2.5068
• Return can pass multiple output
• Separate output with a comma 18
Functions - return terminates a function
def someFun():
print("Let us have some fun")
return None
print('This will never get printed')
in : someFun()
out: Let us have some fun
19
Functions - Flexible arguments
Sometimes you might want to create a function where you pass flexible
arguments
def catchAll(*args, **kwargs):
'''
A catch all function to demonstrate
arguments and keywords
args is a tuple of the arguments passed to the function
kwargs is a dictionary of the keywords passed
'''
print('args', args)
print('kwargs', kwargs)
in : catchAll(1,2,3,4,a=7.0,b=3.7)
out: args (1, 2, 3, 4)
kwargs {'b': 3.7, 'a': 7.0} 20
lambda functions
Use lambda to create quick one line functions
square = lambda x, y, z: x**2 + y**2 + z**2
this creates a function square that we can call
in : square(1,2,3)
out: 14
21