7/19/2020
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
Results Number / Number /
Variable Variable
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
Highest Operator Description
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
Augmented Assignment Operators
Variable
+= Number / Variable
• Augmented assignment can be
used in other mathematics
computation as well:
– Decrement: minus off a value
and store back to the same
variable
x -= 2 equivalent to x = x - 2
– Multiplying: multiply a value
and store back to the same
variable
x *= 2 equivalent to x = x * 2
– Dividing: divide a value and
store back to the same variable
x /= 2 equivalent to x = x / 2
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
Python Standard Library
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. E.g. input(),
print(), int().
Module
● A collection of codes.
● A python program file.
Import a module
● Re-use proven program by including the module in another
program. OR
● General import module_name from math import * # import everything
Syntax: module_name.some_constant some_constant
module_name.some_function() some_function() 9
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
Assignment versus equality
● Assignment operator assigns value on the right to the variable on
the left.
○ =
● Equality operator compares and results in Boolean value
○ ==
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 due to User Input
Exception is thrown when user’s input is invalid.
28
28
14
7/19/2020
Fixing Exception Raised
29
29
Exceptions and Errors
● Exceptions and errors are part and parcel of coding.
● Exceptions and errors due to syntax errors should be fixed during
code development.
● Errors due to user entry or other manageable factors should be
mitigated through the use of try and except.
30
30
15
7/19/2020
You have learnt...
1. To use mathematical operators to manipulate numbers in python.
2. The shortcut operators, augmented operators.
3. Different types of comparison operators to construct if condition
4. Compound or Boolean operators to combine multiple expressions
5. Debugging techniques
6. Errors and Exception
7. The way to manage exception
31
31
16