0% found this document useful (0 votes)
20 views33 pages

Lecture03 Slides

The document contains slides about coding constructs from a lecture. It discusses selection statements like if, elif, else for conditional execution. It also covers iteration statements like for and while loops. For loops are used when the number of iterations is known, while while loops repeat an operation until a condition is met. The slides provide examples of using if/else statements, for loops to iterate over lists, enumerate to get indexes and values, and while loops. It also discusses break and continue keywords for loop control and else clauses.

Uploaded by

tonggennn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views33 pages

Lecture03 Slides

The document contains slides about coding constructs from a lecture. It discusses selection statements like if, elif, else for conditional execution. It also covers iteration statements like for and while loops. For loops are used when the number of iterations is known, while while loops repeat an operation until a condition is met. The slides provide examples of using if/else statements, for loops to iterate over lists, enumerate to get indexes and values, and while loops. It also discusses break and continue keywords for loop control and else clauses.

Uploaded by

tonggennn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

01/10/2023, 16:05 Lecture03 slides

Attendance
Register at: http://go.qub.ac.uk/finattend4

Campus Code: XXXX


01/10/2023, 16:05 Lecture03 slides

Coding Constructs
Content Outline
Selection
Iteration
Comprehension
Errors and Exception handling
01/10/2023, 16:05 Lecture03 slides

Compound Statements
Compound statements contain multiple statements (a block of code)
Affect flow of execution (allow non-linear sequencing)
Can consist of one or more clauses
Use : and indentation
01/10/2023, 16:05 Lecture03 slides

Selection
Selection is the name used in coding for performing actions
conditionally
Certain code is only executed if something is True (or not True )
Implemented using if statements
Results in code branching
Relies on a Boolean test being performed
a>b
a>=b
a==b
a!=b
a in A
Use and , or , not when multiple criteria are required.
01/10/2023, 16:05 Lecture03 slides
01/10/2023, 16:05 Lecture03 slides

if if else if elif else


01/10/2023, 16:05 Lecture03 slides

In [1]: #Execute statements only if test is true


baskettotal = 65

if (baskettotal>=50):
print("You have qualified for free shipping")

You have qualified for free shipping


01/10/2023, 16:05 Lecture03 slides

In [2]: #Execute statements only if test is true


#Otherwise do something else
baskettotal = 45

if (baskettotal>=50):
print("You have qualified for free shipping")
else:
print("The shipping charge is £5")

The shipping charge is £5


01/10/2023, 16:05 Lecture03 slides

In [3]: #Multiple tests


#Path determined by first test that is true
baskettotal = 45

if (baskettotal>=50):
print("You have qualified for free shipping")
elif (baskettotal>=40):
print(f"Spend £{50-baskettotal} more for free shipping")
else:
print("The shipping charge is £5")

Spend £5 more for free shipping


01/10/2023, 16:05 Lecture03 slides

Can have as many elif clauses as required


Prefer elif where branches are mutually exclusive (rather than
sequential if s)
Nesting of if statements also possible (one if statement inside
another)
01/10/2023, 16:05 Lecture03 slides

Simple selection logic can be treated inline


In [4]: #Single line if statement
strikes = 3
if (strikes==3): print("you're outta here!")

you're outta here!


01/10/2023, 16:05 Lecture03 slides

In [5]: #Inline if statement

price = 100
onSale = True

discount = (price * 0.2) if onSale else 0


print("discount =", discount)

discount = 20.0
01/10/2023, 16:05 Lecture03 slides

Iteration
Use when you want to repeat an operation multiple times
for loops
use when number of iterations is known in advance
one iteration for each value in a sequence
use of a loop counter to track position in sequence
can use in combination with enumerate
while loops
use when the operation should be repeated while something is
True or until some condition is met
must ensure that the stopping criteria will eventually occur to
avoid infinite loops
01/10/2023, 16:05 Lecture03 slides

In [6]: #When you just want to repeat an operation a certain number of times

#Prints numbers 0 to 4
for i in range(5):
print(i, end=" ")

0 1 2 3 4
01/10/2023, 16:05 Lecture03 slides

In [7]: #Ranges can also be used to enumerate lists for processing


#Here we use indexing to access the elements in the list

A = [1,3,5,7,9]

for i in range(len(A)):
print(A[i], end=" ")

1 3 5 7 9
01/10/2023, 16:05 Lecture03 slides

In [8]: #When you want to process each element in a list


#and only care about the value (not it's index position)

A = [2,4,6,8,10]

for x in A:
print(x, end=" ")

2 4 6 8 10
01/10/2023, 16:05 Lecture03 slides

In [9]: #When the value and its index position are important

A = [2,4,6,8,10]

for index, value in enumerate(A):


print(f'The value as position {index} is {value}')

The value as position 0 is 2


The value as position 1 is 4
The value as position 2 is 6
The value as position 3 is 8
The value as position 4 is 10
01/10/2023, 16:05 Lecture03 slides

In [10]: #Enumerate has an optional second input parameter defaulted to 0

r = 0.05
cashflows = [5, 5, 105]

#Indexing will now start at 1 not zero!


for t, cf in enumerate(cashflows, 1):
dcf = cf/(1+r) ** t
print(t, f'{dcf:>5.2f}')

1 4.76
2 4.54
3 90.70
01/10/2023, 16:05 Lecture03 slides

Two keywords provide extra control options


break terminates iteration entirely; execution resumes after
the loop
continue terminates that iteration; execution resumes on the
next loop
If using break you can add an else clause
this will only be executed if the break never is
01/10/2023, 16:05 Lecture03 slides

In [11]: #Print numbers 0 to 9 except 5

for i in range(10):
if i==5:
continue
print(i, end=" ")

0 1 2 3 4 6 7 8 9
01/10/2023, 16:05 Lecture03 slides

In [12]: #Print numbers 0 to 4

for i in range(10):
if i==5:
break
print(i, end=" ")

0 1 2 3 4
01/10/2023, 16:05 Lecture03 slides

In [13]: #Else for a loop - only used if break never encountered


A = [1, 2, 3]

for x in A:
if x < 0:
break
print(x, end=" ")
else:
print("\nall positive values")

1 2 3
all positive values
01/10/2023, 16:05 Lecture03 slides

while
01/10/2023, 16:05 Lecture03 slides

In [14]: #Print numbers 0 to 9

i = 0
while i<10:
print(i, end=" ")

#Take control for advancing loop counter


i = i+1

0 1 2 3 4 5 6 7 8 9
01/10/2023, 16:05 Lecture03 slides

Comprehension
Comprehension allows lists to quickly be created from other lists
Simultaneous transformation and filtering
Permits if and if/else logic
Consider using lambda functions
General syntax: [f(x) for x in A] where A is a list and f is a
function
01/10/2023, 16:05 Lecture03 slides

In [15]: #Create list


A = list(range(1,11))
print(f"{A=}")

#Find squares of A
B = [x*x for x in A]
print(f"{B=}")

#Find even numbers in A


C = [x for x in A if (x % 2 == 0)]
print(f"{C=}")

#Change sign of odd numbers


D = [x if (x % 2 == 0) else -x for x in A ]
print(f"{D=}")

A=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
B=[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
C=[2, 4, 6, 8, 10]
D=[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
01/10/2023, 16:05 Lecture03 slides

In [16]: #Using enumerate


CF = [5, 5, 105]; y = 0.03
txt = [f'{i:2.0f} {c:8.2f} {c/(1+y)**i:8.2f}'
for i, c in enumerate(CF,1)]

print("\n".join(txt))

1 5.00 4.85
2 5.00 4.71
3 105.00 96.09
01/10/2023, 16:05 Lecture03 slides

Errors
Developers are human and make coding mistakes
Developers refer to these as bugs
erroneous code must be debugged to pinpoint and correct the
problem code
A good IDE will make this process easier
Good developers:
follow practices to minimise occurance
know how to debug efficiently
add defensive code in anticipation of errors
01/10/2023, 16:05 Lecture03 slides

Error Types
Syntax errors
syntactically invalid code that cannot be executed
should be highlighted by a good IDE
Runtime errors
syntactically valid code that fails when run
for example because you use a str variable in a mathematical
operation
Logical errors
code that doesn't do what it was supposed to (in all cases)
Human error
code works as designed but fails with unintended usage
01/10/2023, 16:05 Lecture03 slides

Exception Handling
Ideally your code would never encounter any runtime errors
But if it does you want it to handle these gracefully
Basic idea of error handling: 'trial and error'
try to run your code
if it doesn’t work you deal with the error
Achieved using a try except block
See https://docs.python.org/3/tutorial/errors.html
01/10/2023, 16:05 Lecture03 slides

In [17]: a = 6; b = 0;

try:
#code where an error might occur
res = a/b

except ZeroDivisionError:
print('I know what went wrong...')

except:
print('something else went wrong...')
#you can create your own errors using raise
raise RuntimeError('my custom exception message')

I know what went wrong...


01/10/2023, 16:05 Lecture03 slides

Appendix
Check list
Can you:
[ ] construct an if statement including elif and else clauses?
[ ] construct a for loop using a range or list ?
[ ] construct a while loop?
[ ] explain what continue and break commands do?
[ ] apply filtering and data maniplution using comprehension?
[ ] apply error handling to prevent runtime errors
01/10/2023, 16:05 Lecture03 slides

Resources
https://docs.python.org/3/reference/compound_stmts.html
https://www.w3schools.com/python/python_conditions.asp
https://www.w3schools.com/python/python_for_loops.asp
https://www.w3schools.com/python/python_while_loops.asp
https://docs.python.org/3/tutorial/errors.html

You might also like