Lecture03 Slides
Lecture03 Slides
Attendance
Register at: http://go.qub.ac.uk/finattend4
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 (baskettotal>=50):
print("You have qualified for free shipping")
if (baskettotal>=50):
print("You have qualified for free shipping")
else:
print("The shipping charge is £5")
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")
price = 100
onSale = True
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
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
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]
r = 0.05
cashflows = [5, 5, 105]
1 4.76
2 4.54
3 90.70
01/10/2023, 16:05 Lecture03 slides
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
for i in range(10):
if i==5:
break
print(i, end=" ")
0 1 2 3 4
01/10/2023, 16:05 Lecture03 slides
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
i = 0
while i<10:
print(i, end=" ")
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
#Find squares of A
B = [x*x for x in A]
print(f"{B=}")
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
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')
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