S02 Notes
S02 Notes
S02 Notes
Seminar 2:
Operators in Python
Revisit - Program
● A program is a list of
statements.
● Statement contains
definition, assignment,
expression.
● Elements of
programming:
○ Variables (words)
○ Controls
(sequence)
○ Functions (repeat
a set of sequence)
This session: Make variants of statements for
computation and comparison
1
7/19/2020
Mathematical Operators
• Giving instruction for computer to do mathematics.
• The mathematical operation results in end number that
can then be stored in variable.
• Mathematical operators can be used directly on
numbers: x = 1 + 2
• It can also be used on variables: y = x * x
Maths Operators
1. Addition +
2. Subtraction -
3. Multiplication *
4. To the power of **
5. Float division /
6. Integer division // Which
operator to
7. Modulus/Remainder % run first????
2
7/19/2020
Orders of operators
PEMDAS Rule
precedence ** Raise to the power of
~ + ‐ Complement, unary plus and negate
* / % // Multiply, divide, modulo and floor division
+ ‐ Addition and subtraction
>> << Right and left bitwise shift
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= ‐= += *= **= Assignment operators
is, is not Identity operators
in, not in Membership operators
not, or, and Logical operators
Lowest
precedence
Augmented Assignment
Operators
• Giving instruction for computer to:
– Retrieve the value stored in the variable.
– Compute the mathematics based on the value after operator.
– Store back the result in the same variable.
• Mathematical operators can be used directly on numbers: x += 1
• It can also be used on variables: y += x
Number Number
Results /
Variable
/
Variable +=
3
7/19/2020
Module
Library
● A collection of modules (python files)
● Python comes with a set of default library called standard library, it
can be used readily, does not need to be imported.
Module
● A collection of codes.
● A python program file.
Import a module
● Re-use proven program by including the module in another
program.
● General Syntax:
import module_name from math import * # import everything
module_name.some_constant OR some_constant
8
module_name.some_function() some_function()
4
7/19/2020
Other
Importing math module functions
from math
library
import math
● Contains some useful maths functions and constants. math.pi
math.e
● Can be combined with other data for maths operations. math.exp(x)
math.log(x)
math.log10(x)
math.log2(x)
math.log(x, y)
math.floor(x)
math.ceil(x)
math.fabs(x)
math.pow(x,y)
math.sqrt(x)
math.factorial(x)
10
10
5
7/19/2020
Decision making
● Sequential program: ● Indentation and Branching:
11
11
Decision making
● Sequential program: ● Indentation and Branching:
12
12
6
7/19/2020
Decision -> if
• Decision involves comparison.
• Compare numbers, compare texts.
• Compare using comparison operators to
results in Boolean values (True / False).
• Decision can be reached by using if, for, and
while loop.
• Loop will be executed when the comparison
results in True.
13
13
if condition
• Test the comparison condition then execute body if it is True.
• Structure:
if condition:
body
elif condition:
body
else:
body
14
14
7
7/19/2020
If condition
Error Checking
Criteria Checking
15
15
Comparison Operators
● Compare the expression on both sides
● To give two possible Boolean outcomes: True False
● Provide control through comparison, for example if comparison.
● Operators: < , > , <= , >= , == , !=
16
16
8
7/19/2020
17
17
Logical Operators
● Combine multiple decisions -> Compound decision
● To give two possible Boolean outcomes at the end: True False
● Operators:
○ and (True only when both sides are true).
18
18
9
7/19/2020
Logical Operators
● Operators:
○ or (True if any side isTrue)
19
19
Logical Operators
● Operators:
○ not
20
20
10
7/19/2020
Special Operators
● Operators:
○ is
○ is not
○ in
○ not in
21
21
Errors in Python
Syntax Error
Runtime Error
Logical Error
22
22
11
7/19/2020
Error
Syntax Error Runtime Error
• Typo in codes that prevents • Program fails due to invalid
the program from running. user entry when running.
• Indentation problem, not • Program not able to perform
indented correctly. certain functions correctly
• Brackets problems, open like converting string to float
bracket not closed. number etc.
• End of statement colon, :, • Use try, except block.
not specified after if, elif,… • Try to embed the codes
likely to fail.
• Except with matching error
to handle the error with
appropriate error message.23
23
Error
Logical Error
• Error due to logic issues • Program with logical error
in the codes, for example, is still runnable, it does
using the wrong formula not show warning or error
to calculate, passing the signs.
wrong variables to the • It is detected through
functions etc. examining the output
being different from
expected results.
24
24
12
7/19/2020
Debugging
● Sample program for debugging.
25
25
Errors
ValueError: A type of exception or error raised when the wrong type of arguments are passed.
To fix this: Check the line with error, confirm the type of input required for each function call.
26
26
13
7/19/2020
Types of Exceptions
Read up information on the link, add in explanation for the Exception in
the following table:
https://docs.python.org/3/library/exceptions.html
Exception Explain
AttributeError
ImportError
IndexError
KeyError
IndentationError
TypeError
ValueError
ZeroDivisionError
IOError 27
27
Exception is thrown when user’s input is invalid.
28
28
14
7/19/2020
29
29
30
30
15
7/19/2020
31
31
16