0% found this document useful (0 votes)
1 views57 pages

Chapter 3 - Complex Data Type (Python)

Uploaded by

yy526zx813
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)
1 views57 pages

Chapter 3 - Complex Data Type (Python)

Uploaded by

yy526zx813
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

PROGRAMMING

SCIENTIFIC
SKEE1033
COMPLEX DATA
TYPE
( WEEK 3 )

DR. AHMAD SHAHIDAN ABDULLAH


DR. AHMAD SHARMI ABDULLAH
DR. AMIRJAN NAWABJAN
DR. MOHD ADIB SARIJARI
DR. MUHAMMAD AL FARABI MUHAMMAD IQBAL
DR. MUHAMMAD ARIFF BAHARUDIN
PM. IR. TS. DR. ASRUL IZAM AZMI
PM. IR. TS. DR. MICHAEL TAN LOONG PENG
OBJECTIVES

 To understand the operation of arithmetic expression on both matrix


and array operators.
 To understand the operation of Boolean expression on both relational
and logical operators.

SKEE 1033 2
OPERATION

STATEMENT FUNCTION

1. ASSIGNMENT Group of statement


syntax
that perform a task
Assign array to a variable using syntax
EQUAL OPERATOR def function_name(input1, input2):
variable = expression # Code block
return output
2. REPITITION Arithmetic

TYPE
Execute statements specified Boolean
number of times using
while COMMAND
BOOLEAN OPERATOR
or ITERATION PROTOCOL for
Direct instructions
often used in the
syntax command line
3. DECISION
Execute statements if if REPL: Read-Eval-Print Loop, which
condition is TRUE using if-else is an interactive programming
if-elif-else environment that takes single user
BOOLEAN OPERATOR
inputs (commands), evaluates them,
and returns the result to the user.
SKEE 1033
3
ARITHMETIC OPERATION
INTRODUCTION

• Python, particularly with libraries like NumPy, supports two main types of
arithmetic operations: element-wise operations and matrix operations.
• Matrix operations
 Use @ operator or functions like [Link]() , [Link]() and
[Link] for linear algebra rules
• Element-wise (Array) Operations:
 Execute computations on each corresponding element and support
multidimensional arrays.
• The differentiation between element-wise and matrix operations is
explicit.
• Element-wise operations use standard arithmetic operators (+, -, *, /)
when working with NumPy arrays.
• Both element-wise and matrix operations are the same for addition (+)
and subtraction (-).

SKEE 1033 5
ARITHMETIC OPERATOR
Matrix and element-wise operation in Python (NumPy)
Operation Algebraic Python Matrix Operation Python Array (Element-wise)
Operation
Addition 𝑎𝑎 + 𝑏𝑏 𝑎𝑎 + 𝑏𝑏 𝑎𝑎 + 𝑏𝑏
Subtraction 𝑎𝑎 − 𝑏𝑏 𝑎𝑎 − 𝑏𝑏 𝑎𝑎 − 𝑏𝑏
Division 𝑎𝑎/𝑏𝑏 N/A 𝑎𝑎/𝑏𝑏
Multiplication 𝑎𝑎 × 𝑏𝑏 𝑎𝑎 @ 𝑏𝑏 or [Link](𝑎𝑎, 𝑏𝑏) 𝑎𝑎 ∗ 𝑏𝑏
Right Division (A / B) 𝑋𝑋𝑋𝑋 = 𝑏𝑏 [Link](a. T, b. T). T N/A
Left Division (A \ B) 𝑎𝑎𝑎𝑎 = 𝑏𝑏 [Link](a, b) N/A
Power 𝑎𝑎𝑏𝑏 [Link].matrix_power(𝑎𝑎, 𝑏𝑏) 𝑎𝑎∗∗ 𝑏𝑏
Transpose 𝑎𝑎T 𝑎𝑎. T N/A
Precedence
Order Operation
1 Parentheses

2 Power
3 Transpose
4 Multiplication & Division, left to right
5 Addition & Subtraction
6 Colon : (Slice Operation)

SKEE 1033 6
SKEE 1033 7
KEY DIFFERENCES BETWEEN
[Link] AND [Link] IN NUMPY

 Dimensionality
 [Link]: Multi-dimensional (1D, 2D, 3D, etc.)
 [Link]: Always 2D (rows and columns)

 Multiplication Handling
 [Link]: * is element-wise multiplication. Use @ or [Link]() for matrix
multiplication
 [Link]: * is matrix multiplication

 Type of Object
 [Link]: Slicing retains the same array type.
 [Link]: Always returns a 2D matrix when sliced.

 Recommendation
 [Link]: More flexible and preferred for most tasks.
 [Link]: Legacy; less common in modern projects.

SKEE 1033 8
MATRIX OPERATOR
MATRIX OPERATION
 Example 1: Python script that demonstrates only matrix operations,
focusing on addition, subtraction, multiplication, right division, left
division, power, and transpose using NumPy.
import numpy as np

# Define two 2x2 matrices


A = [Link]([[1, 2], [3, 4]])
B = [Link]([[5, 6], [7, 8]])

print("Matrix A:")
print(A)
Matrix A:
[[1 2]
[3 4]]

print("\nMatrix B:")
print(B)
Matrix B:
[[5 6]
[7 8]]

SKEE 1033 10
MATRIX OPERATION
 Example 1 (continued):
# 1. Matrix Addition Matrix A: Matrix B:
matrix_add_result = A + B [[1 2] [[5 6]
print("\nMatrix Addition (A + B):") [3 4]] [7 8]]
print(matrix_add_result)
Matrix Addition (A + B):
[[ 6 8]
[10 12]]

# 2. Matrix Subtraction
matrix_sub_result = A - B
print("\nMatrix Subtraction (A - B):")
print(matrix_sub_result)

Matrix Subtraction (A - B):


[[-4 -4]
[-4 -4]]

SKEE 1033 11
MATRIX OPERATION
 Example 1 (continued):
# 3. Matrix Multiplication Matrix A: Matrix B:
# Using @ operator [[1 2] [[5 6]
matrix_mul_result = A @ B [3 4]] [7 8]]
print("\nMatrix Multiplication (A @ B):")
print(matrix_mul_result)

Matrix Multiplication (A @ B):


[[19 22]
[43 50]]

# Alternatively, using [Link]()


matrix_mul_result_alt = [Link](A, B)
print("\nMatrix Multiplication ([Link](A, B)):")
print(matrix_mul_result_alt)

Matrix Multiplication ([Link](A, B)):


[[19 22]
[43 50]]

SKEE 1033 12
MATRIX OPERATION
 Example 1 (continued):
# 4. Matrix Right Division
# Solving XA = B using [Link] (interpreted as A / B)
matrix_right_div_result = [Link](A.T, B.T).T Matrix A: Matrix B:
print("\nMatrix Right Division ([Link](A.T, B.T).T):") [[1 2] [[5 6]
print(matrix_right_div_result) [3 4]] [7 8]]
Matrix Right Division ([Link](A.T, B.T).T):
[[-1. 2.]
[-2. 3.]]

# 5. Matrix Left Division


# Solving AX = B using [Link] (interpreted as A \ B)
matrix_left_div_result = [Link](A, B)
print("\nMatrix Left Division ([Link](A, B)):")
print(matrix_left_div_result)

Matrix Left Division ([Link](A, B)):


[[-3.
\\ -4.]
[ 4. 5.]]

SKEE 1033 13
MATRIX OPERATION
 Example 1 (continued):
# 6. Matrix Power
# Using [Link].matrix_power() to raise matrix A to the power of 2
matrix_power_result = [Link].matrix_power(A, 2) Matrix A: Matrix B:
print("\nMatrix Power ([Link].matrix_power(A, 2)):") [[1 2] [[5 6]
print(matrix_power_result) [3 4]] [7 8]]
Matrix Power ([Link].matrix_power(A, 2)):
[[ 7 10]
[15 22]]

# 7. Matrix Transpose
transpose_result = A.T
print("\nMatrix Transpose (A.T):")
print(transpose_result)

Matrix Transpose (A.T):


[[1 3]
[2 4]]

SKEE 1033 14
MATRIX : PRECEDENCE

• Transpose vs. Multiplication:


The transpose is done before multiplication (A.T @ B).
• Parentheses:
Parentheses force specific calculations to be done first ((A + B) @ B).
• Power Precedence:
The power operation is performed before multiplication
([Link].matrix_power(A, 2) @ B).
• Multiplication vs. Division:
Multiplication within matrices happens before division using
[Link]().
• Addition vs. Multiplication:
Multiplication takes precedence over addition (A @ B + B).
• Combining Multiple Operations:
A complex expression demonstrates how Python respects the set
precedence rules for correct evaluation.

SKEE 1033 15
MATRIX : PRECEDENCE
 Example 2: Python script that demonstrates the precedence of
operations like addition, multiplication, transpose, power, and division
when combined in a single expression. Understanding precedence helps
predict the order in which operations are evaluated.
import numpy as np

# Define two 2x2 matrices


A = [Link]([[1, 2], [3, 4]])
B = [Link]([[5, 6], [7, 8]])

print("Matrix A:")
print(A)
Matrix A:
[[1 2]
[3 4]]
print("\nMatrix B:")
print(B)

Matrix B:
[[5 6]
[7 8]]

SKEE 1033 16
MATRIX : PRECEDENCE
 Example 2 (continued):
Matrix A: Matrix B:
# 1. Demonstrate Precedence of Transpose vs Multiplication
[[1 2] [[5 6]
# Transpose happens before multiplication
[3 4]] [7 8]]
precedence_result_1 = A.T @ B
print("\nPrecedence 1 (Transpose before Multiplication - A.T @ B):")
print(precedence_result_1)
Precedence 1 (Transpose before Multiplication - A.T @ B):
[[26 30]
[38 44]]
# 2. Demonstrate Precedence of Parentheses
# Parentheses change the order of operations
precedence_result_2 = (A + B) @ B
print("\nPrecedence 2 (Parentheses first - (A + B) @ B):")
print(precedence_result_2)

Precedence 2 (Parentheses first - (A + B) @ B):


[[ 86 100]
[134 156]]

SKEE 1033 17
MATRIX : PRECEDENCE
 Example 2 (continued):
Matrix A: Matrix B:
# 3. Demonstrate Power Precedence
[[1 2] [[5 6]
# Power operation happens before multiplication
[3 4]] [7 8]]
precedence_result_3 = [Link].matrix_power(A, 2) @ B
print("\nPrecedence 3 (Power before Multiplication - [Link].matrix_power(A, 2) @
B):")
print(precedence_result_3)
Precedence 3 (Power before Multiplication - [Link].matrix_power(A, 2) @ B):
[[105 122]
[229 266]]

# 4. Demonstrate Multiplication and Division Precedence


# Multiplication happens before solving division operations
precedence_result_4 = [Link](B.T, (A @ B).T).T
print("\nPrecedence 4 (Multiplication before Division - [Link](B.T, (A @
B).T).T):")
print(precedence_result_4)
Precedence 4 (Multiplication before Division - [Link](B.T, (A @ B).T).T):
[[1. 2.]
[3. 4.]]

SKEE 1033 18
MATRIX : PRECEDENCE
 Example 2 (continued):
Matrix A: Matrix B:
# 5. Demonstrate Precedence of Addition and Multiplication
[[1 2] [[5 6]
# Multiplication happens before addition
[3 4]] [7 8]]
precedence_result_5 = A @ B + B
print("\nPrecedence 5 (Multiplication before Addition - A @ B + B):")
print(precedence_result_5)

Precedence 5 (Multiplication before Addition - A @ B + B):


[[24 28]
[50 58]]

# 6. Combining Multiple Precedence


# Complex combination to demonstrate full precedence
precedence_result_6 = ([Link].matrix_power(A, 2) + A.T) @ [Link](B, A)
print("\nPrecedence 6 (Combination of Power, Transpose, Addition, and Division):")
print(precedence_result_6)

Precedence 6 (Combination of Power, Transpose, Addition, and Division):


[[-12. -7.]
[-19. -10.]]

SKEE 1033 19
ARRAY OPERATOR
ARRAY OPERATION
 Example 3: This script focuses solely on element-wise addition, subtraction,
multiplication, division, power
import numpy as np

# Define two 2x2 arrays


A = [Link]([[1, 2], [3, 4]])
B = [Link]([[5, 6], [7, 8]])

print("Array A:")
print(A)
Matrix A:
[[1 2]
[3 4]]

print("\nArray B:")
print(B)

Matrix B:
[[5 6]
[7 8]]

SKEE 1033 21
ARRAY OPERATION
 Example 3 (continued):
# 1. Element-wise Addition Matrix A: Matrix B:
element_wise_add = A + B [[1 2] [[5 6]
print("\nElement-wise Addition (A + B):") [3 4]] [7 8]]
print(element_wise_add)
Element-wise Addition (A + B):
[[ 6 8]
[10 12]]

# 2. Element-wise Subtraction
element_wise_sub = A - B
print("\nElement-wise Subtraction (A - B):")
print(element_wise_sub)

Element-wise Subtraction (A - B):


[[-4 -4]
[-4 -4]]

SKEE 1033 22
ARRAY OPERATION
 Example 3 (continued):
# 3. Element-wise Multiplication Matrix A: Matrix B:
element_wise_mul = A * B [[1 2] [[5 6]
print("\nElement-wise Multiplication (A * B):") [3 4]] [7 8]]
print(element_wise_mul)
Element-wise Multiplication (A * B):
[[ 5 12]
[21 32]]
# 4. Element-wise Right Division
element_wise_right_div = A / B
print("\nElement-wise Right Division (A / B):")
print(element_wise_right_div)

Element-wise Right Division (A / B):


[[0.2 0.33333333]
[0.42857143 0.5 ]]

SKEE 1033 23
ARRAY OPERATION
 Example 3 (continued):
# 5. Element-wise Left Division Matrix A: Matrix B:
element_wise_left_div = B / A [[1 2] [[5 6]
print("\nElement-wise Left Division (B / A):") [3 4]] [7 8]]
print(element_wise_left_div)
Element-wise Left Division (B / A):
[[5. 3. ]
[2.33333333 2. ]]

# 6. Element-wise Power
element_wise_power = A ** 2
print("\nElement-wise Power (A ** 2):")
print(element_wise_power)
Element-wise Power (A ** 2):
[[ 1 4]
[ 9 16]]

SKEE 1033 24
ARRAY SIZE AND RELATED ATTRIBUTES
 Example 4: This script retrieves the size and shape of arrays, including the
shape, total number of elements, number of dimensions, and size of each
dimension.
import numpy as np

# Define an array (2x2)


A = [Link]([[1, 2], [3, 4]])
print("Array A:")
print(A)
Matrix A:
[[1 2]
[3 4]]

# Shape of the array (rows, columns)


array_shape = [Link]
print("\nShape of the array (rows, columns):")
print(array_shape) # (2, 2)
Shape of the array (rows, columns):
(2, 2)

SKEE 1033 25
ARRAY SIZE AND RELATED ATTRIBUTES
 Example 4 (continued):
# Total number of elements in the array Matrix A:
array_size = [Link] [[1 2]
print("\nTotal number of elements in the array:") [3 4]]
print(array_size) # 4
Total number of elements in the array:
4

# Number of dimensions of the array


array_ndim = [Link]
print("\nNumber of dimensions of the array:")
print(array_ndim) # 2

Number of dimensions of the array:


2

# Size of each dimension


rows = len(A) # Number of rows
columns = len(A[0]) # Number of columns
print("\nSize of each dimension:")
print(f"Rows: {rows}, Columns: {columns}")

Size of each dimension:


Rows: 2, Columns: 2

SKEE 1033 26
VECTORIZING : COMPOUND INTEREST

 In Python, using NumPy arrays allows you to calculate values for multiple inputs at
once, a technique called vectorization. This means you can perform operations on
entire arrays without writing loops, making the code faster and simpler.
 Example 5
 Lets consider a formula of compound interest as below where 𝐴𝐴 = invested money, 𝑟𝑟 =
interest rate, 𝑛𝑛 = total year, and 𝐵𝐵 = final balance:
𝑛𝑛
𝐵𝐵 = 𝐴𝐴 1 + 𝑟𝑟
 Single Value Calculation:
If 𝐴𝐴 = 100,then using 𝑟𝑟 = 0.09 and 𝑛𝑛 = 10m , then scalar will result 𝐵𝐵 = 236.7.
 Vectorized Calculation:
To compute 𝐵𝐵 for several values of 𝐴𝐴 without repeating the calculation multiple times, we can
represent A as an array

𝐴𝐴 = [100, 200, 500, 1000, 4000]


 Thus, evaluating 𝐵𝐵 based on the vector 𝐴𝐴 will give
𝐵𝐵 = [236.7, 473.5, 1183.7, 2367.4, 9469.5]

SKEE 1033 27
VECTORIZING : COMPOUND INTEREST
 Python Code:
import numpy as np
# Define interest rate and number of years
r = 0.09; n = 10

# Single invested value


A1 = 100

# Calculate final balance for the single value


B1 = A1 * (1 + r) ** n
print("Single value calculation:")
print(f"B1 = {B1:.4f}") # Output: 236.7364
Single value calculation:
B1 = 236.7364
# Vectorized invested values
A2 = [Link]([100, 200, 500, 1000, 4000])

# Calculate final balances for each value in the array


B2 = A2 * (1 + r) ** n
print("\nVectorized calculation with multiple values:")
print("B2 =", [Link](B2, 4)) # Output: [236.7, 473.5, 1183.7, 2367.4, 9469.5]

Vectorized calculation with multiple values:


B2 = [ 236.7364 473.4727 1183.6818 2367.3637 9469.4547]

SKEE 1033 28
VECTORIZING : VERTICAL DISPLACEMENT

 Example 6: If a stone is thrown vertically upward, its vertical


displacement s after an elapsed time t is given by the formula

𝑠𝑠 = 𝑔𝑔𝑡𝑡 2 /2
where:

g is the acceleration due to gravity with value 9.81.


t is time elapsed

Calculate the displacement (s) for different elapsed times using


vectorized operations.

The structure plan for this problem is as follows:


1. Assign the data (g and t) to variables.
2. Calculate the value of s for each time value in t.

SKEE 1033 29
VECTORIZING : VERTICAL DISPLACEMENT

 Example 6 (continued): Perform the calculations using NumPy


import numpy as np

# Step 1: Assign values to variables


g = 9.81 # acceleration due to gravity
# Vectorize t for time intervals
t = [Link](0, 6) # Creates an array [0, 1, 2, 3, 4, 5]

# Step 2: Calculate the displacement s using the formula


s = g * t**2 / 2 # Performs element-wise squaring and multiplication

# Display the results


print("Elapsed time (t):", t) # Shows time intervals

Elapsed time (t): [0 1 2 3 4 5

print("Displacement (s):", [Link](s, 4)) # Displays the calculated displacements

Displacement (s): [ 0. 4.905 19.62 44.145 78.48 122.625]

SKEE 1033 30
VECTORIZING : VOLUME OF CONES

 Example 7: For some values of D and H, the python code will be as


follow:
import numpy as np

# Define arrays of diameters and heights for 5 different cones


D = [Link]([3, 5, 7, 9, 11]) # Example diameters
H = [Link]([4, 6, 8, 10, 12]) # Example heights

# Calculate the volumes using vectorized operations


V = (1/12) * [Link] * D**2 * H

# Display the calculated volumes


print("Volumes of cones using vectorization:")
Volumes of cones using vectorization:
print([Link](V, 4)) # Rounded to four decimal places

[ 9.4248 39.2699 102.6254 212.0575 380.1327]

SKEE 1033 31
COMPLEX NUMBER ARITHMETIC

1. Complex Numbers in Python:


• A complex number is represented as 𝑎𝑎 + 𝑏𝑏𝑏𝑏 where 𝑗𝑗 is the imaginary unit
(sqrt(-1)).
• 𝑎𝑎 and 𝑏𝑏 are real numbers

2. Complex Matrix Operations:


• Conjugate Transpose ('): In Python, the conjugate transpose is called using
.conj().T.
• Pure Transpose (.'): In Python, this operation is simply .T

SKEE 1033 32
COMPLEX NUMBER ARITHMETIC

 Example 8: Handling complex numbers using NumPy arrays, focusing


on operations like conjugate transpose and pure transpose.
import numpy as np # Define a 2x2 array with complex numbers
a = [Link]([[1 + 1j, 2 + 2j], [3 + 3j, 4 + 4j]])
print("Array a:"); print(a)
Array a:
[[1.+1.j 2.+2.j]
[3.+3.j 4.+4.j]]
# Conjugate transpose of the array (changes the sign of imaginary parts and transposes)
conjugate_transpose = [Link]().T
print("\nConjugate Transpose of a ([Link]().T):")
print(conjugate_transpose)
Conjugate Transpose of a ([Link]().T):
[[1.-1.j 3.-3.j]
[2.-2.j 4.-4.j]]
# Pure transpose of the array (transposes without changing imaginary parts)
pure_transpose = a.T
print("\nPure Transpose of a (a.T):")
print(pure_transpose)
Pure Transpose of a (a.T):
[[1.+1.j 3.+3.j]
[2.+2.j 4.+4.j]]

SKEE 1033 33
ARITHMETIC OPERATOR DRILL

7 4
𝑎𝑎 = 2; 𝑏𝑏 = 2 4 ; 𝑐𝑐 = ;
1 3

Based on the above, evaluate by hand of the following expressions:


1. a+2-3 9. [Link](c.T,c) 18. [Link](a+2j)
2. a+2*3 10. [Link](a+1,a**3 // 2) 19. (a+2j).T
3. 2*a**3+a 11. ([Link](1,a**3) // 2) 20. [Link]([a+2j,a+3j])
4. a+b 12. [Link](a,a+ 1)*c 21. [Link]([a+2j,a+3j]).T
5. [Link](b,c) 13. c**(2**a)
6. c.T 14. [Link](c, c)
7. [Link](b,c.T) 15. c*c
8. b.T+a/2+2 16. b**b
17. a + b * b**c.T

SKEE 1033 34
BOOLEAN OPERATION
BOOLEAN OPERATOR

 Boolean algebra is a mathematical operation that return a logical value,


which are either True or False.
 Thus, in programming language, the assignment from Boolean
expression will return a logical data type.
 There are two types of Boolean operator in programming language:
1. Relational Operator.
2. Logical Operator.

 Common usage of Boolean operators are:


1. Identify particular elements from an array.
2. Describing decision and repetition statements

SKEE 1033 36
BOOLEAN OPERATOR
Relational Operator Precedence
Symbol Meaning
< Less than
<= Less than or equal
== Equal
!= Not equal
> Greater than
>= Greater than or equal

Logical Operator
Logical Element-wise Short-circuiting
AND & and
OR | or
NOT ~ not

Logical Value
Function Value
true 1
false 0

SKEE 1033 37
TRUTH TABLE FOR LOGICAL OPERATIONS

Input Input AND OR NOT


A B A&B A|B ~A
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0

• In Python, the logical operators and, or, and not work on


logical values (True and False), but they also work on
numerical values, where any nonzero value is considered
True (1) and zero is considered False (0).

SKEE 1033 38
LOGICAL OPERATORS IN PYTHON:
& vs AND, | vs OR, ~ vs NOT
 Logical operators (and, or, not) output True or False depending on the
evaluation of Boolean conditions.
 Bitwise operators (&, |, ~) output numeric results based on bitwise
operations on the binary representations of numbers.
True and False # Output: False
True or False # Output: True
not True # Output: False

6 & 3 # Output: 2 (Binary: 110 & 011 = 010)


6 | 3 # Output: 7 (Binary: 110 | 011 = 111)
~5 # Output: -6 (Binary: 101 becomes -110 in two's complement)

SKEE 1033 39
LOGICAL OPERATORS

 Example 9: Code in Python Using NumPy

import numpy as np Matrix A:


[0 0 1 1]
# Define arrays A and B
A = [Link]([0, 0, 1, 1]) Matrix B:
B = [Link]([0, 1, 0, 1]) [0 1 0 1]

# Element-wise operations
and_result = A & B
or_result = A | B
not_result = ~A

print("Element-wise AND (A & B):", and_result) # Output: [0 0 0 1]


Element-wise AND (A & B): [0 0 0 1]
print("Element-wise OR (A | B):", or_result) # Output: [0 1 1 1]
Element-wise OR (A | B): [0 1 1 1]
print("Element-wise NOT (~A):", not_result) # Output: [1 1 0 0]
Element-wise NOT (~A): [-1 -1 -2 -2]

SKEE 1033 40
RELATIONAL OPERATOR

 Example 10: Relational operator


# Relational Operators in Python a:
[5]
# Define sample variables
a = 5 b:
b = 10 [10]

# Relational operations
less_than = a < b # Less than
less_equal = a <= b # Less than or equal
equal = a == b # Equal
not_equal = a != b # Not equal
greater_than = a > b # Greater than
greater_equal = a >= b # Greater than or equal

# Print results
print("a =", a) print("b =", b)
print("a < b:", less_than) # Output: True
print("a <= b:", less_equal) # Output: True
print("a == b:", equal) # Output: False
print("a != b:", not_equal) # Output: True
print("a > b:", greater_than) # Output: False
print("a >= b:", greater_equal) # Output: False

SKEE 1033 41
RELATIONAL OPERATOR

 Example 10 (continued):
# Print results a:
print("a =", a) print("b =", b) [5]
print("a < b:", less_than) # Output: True
print("a <= b:", less_equal) # Output: True b:
print("a == b:", equal) # Output: False [10]
print("a != b:", not_equal) # Output: True
print("a > b:", greater_than) # Output: False
print("a >= b:", greater_equal) # Output: False

a = 5
b = 10
a < b: True
a <= b: True
a == b: False
a != b: True
a > b: False
a >= b: False

SKEE 1033 42
OPERATORS PRECEDENCE

 Example 11: Operators precedence


# Precedence of Operators in Python a:
# Sample variables [5]
a = 5
b = 2
c = 3 b:
[2]
# Expressions demonstrating operator precedence
expr1 = (a + b) * c # Parentheses first c:
expr2 = a ** b + c # Power first, then addition [3]
expr3 = ~a + b # NOT first, then addition
expr4 = a * b / c # Multiply, then divide
expr5 = a + b - c # Addition, then subtraction
expr6 = a < b and b > c # Relational, then AND
expr7 = a | b and c # Bitwise OR then Logical AND

# Print results
print("Expression 1 ((a + b) * c):", expr1) # Output: (5 + 2) * 3 = 21
print("Expression 2 (a ** b + c):", expr2) # Output: 5**2 + 3 = 28
print("Expression 3 (~a + b):", expr3) # Output: -6 + 2 = -4
print("Expression 4 (a * b / c):", expr4) # Output: 5 * 2 / 3 = 3.3333...
print("Expression 5 (a + b - c):", expr5) # Output: 5 + 2 - 3 = 4
print("Expression 6 (a < b and b > c):", expr6) # Output: False and True = False
print("Expression 7 (a | b and c):", expr7) # Output: 3

SKEE 1033 43
OPERATORS PRECEDENCE

 Example 11 (continued):
# Print results a:
print("Expression 1 ((a + b) * c):", expr1) # Output: (5 + 2) * 3 = 21 [5]
print("Expression 2 (a ** b + c):", expr2) # Output: 5**2 + 3 = 28
print("Expression 3 (~a + b):", expr3) # Output: -6 + 2 = -4
print("Expression 4 (a * b / c):", expr4) # Output: 5 * 2 / 3 = 3.3333... b:
print("Expression 5 (a + b - c):", expr5) # Output: 5 + 2 - 3 = 4 [2]
print("Expression 6 (a < b and b > c):", expr6) # Output: False and True = False
print("Expression 7 (a | b and c):", expr7) # Output: 3 c:
[3]
Expression 1 ((a + b) * c): 21
Expression 2 (a ** b + c): 28
Expression 3 (~a + b): -4
Expression 4 (a * b / c): 3.3333333333333335
Expression 5 (a + b - c): 4
Expression 6 (a < b and b > c): False
Expression 7 (a | b and c): 3

SKEE 1033 44
MIX OPERATORS

 When working with Python, you often need to combine different types
of operations, such as arithmetic, relational, and Boolean logic, in a
single expression. Understanding how these operations interact is
crucial for writing effective and correct code.
 Key Concepts:
• Arithmetic Operations:
• Basic mathematical calculations: addition (+), subtraction (-), multiplication
(*), division (/), modulo (%), and exponentiation (**).
• Relational Operators:
• Used to compare values: less than (<), greater than (>), equal to (==), not equal
to (!=), less than or equal to (<=), and greater than or equal to (>=).
• Boolean Operators:
 Used to combine logical expressions: AND (and), OR (or), and NOT
(not).Short-circuiting: Evaluations stop as soon as the result is determined
(e.g., and stops if the first operand is False).

SKEE 1033 45
MIX OPERATORS

 Example 12: Integrated Arithmetic, Relational, and Boolean Operations


# Mixed Arithmetic, Relational, and Boolean Operations

# Define sample variables


x = 8 ; y = 5 ; z = 12

# Combined operations
# This expression combines arithmetic, relational, and boolean logic
result = ((x + y) > z) and ((x - y) * 2 < z) or (z % y == 0)

# Display the result


print("Combined Result (integrating all operations):", result) # Output will be a boolean value

Combined Result (integrating all operations): True

# Explanation:
# (x + y) > z checks if the sum of x and y is greater than z
# (x - y) * 2 < z) checks if double the difference between x and y is less than z
# (z % y == 0) checks if z is divisible by y (no remainder)

SKEE 1033 46
MIX OPERATORS

 Example 12 (continued):
# Additional mixed calculations
final_result = (x * y < z + 5) or ((x + 2) == (y + 5) and (z // y) > 1)

# Display the final result


print("Final Result (mixed operations):", final_result) # Output will be a boolean value

Final Result (mixed operations): True

# Explanation:
# (x * y < z + 5) checks if the product of x and y is less than z plus 5
# ((x + 2) == (y + 5)) checks if x + 2 equals y + 5
# (z // y) > 1 checks if the integer division of z by y is greater than 1

SKEE 1033 47
CHAINED COMPARISONS

 Chained comparisons allow you to compare multiple values in a single,


readable expression. This enables you to check whether a value falls
within a certain range or if multiple conditions hold true, without
needing to use logical operators such as and repeatedly.
 Why Use Chained Comparisons?
 Readability:
 Chained comparisons improve code readability by expressing
conditions in a natural way.
 Efficiency:
 Python evaluates the conditions from left to right and stops
once a condition is False, which can make chained comparisons
slightly more efficient in some cases.

SKEE 1033 48
CHAINED COMPARISONS

 In traditional comparisons, you might write something like this:


x = 10
if x > 5 and x < 15:
print("x is between 5 and 15")

 With chained comparisons, Python allows you to rewrite this as:


if 5 < x < 15:
print("x is between 5 and 15")

 This expression checks whether x is greater than 5 and less than 15 in


one seamless statement. Chained comparisons are evaluated from left
to right, and Python automatically combines them into a single
condition using logical operators (and).

SKEE 1033 49
CHAINED COMPARISONS

 Chained comparisons can also involve different types of operators:


x = 8
y = 12

if 5 < x < 10 < y < 20:


print("x is between 5 and 10, and y is between 10 and 20")

 In this example, Python checks the conditions sequentially:


5 < x, x < 10, 10 < y, and y < 20.
 If all conditions are met, the expression evaluates to True.

SKEE 1033 50
CHAINED COMPARISONS

 Example 13: Multiple Short Chained Comparisons


# 1. Check if a number is between two values
x = 15 print(10 < x < 20) # True, because 15 is between 10 and 20
True

# 2. Multiple chained comparisons with different operators


y = 25 print(20 < y <= 30)
# True, 25 is greater than 20 and less than or equal to 30
True

# 3. Using mathematical operations inside chained comparisons


a = 4 print(2 < a**2 < 20) # True, 4 squared (16) is between 2 and 20
True

# 4. Chained comparison involving string comparison


name = "Bob"
print("Alice" < name < "Charlie") # True, Bob is alphabetically between Alice and
Charlie
True

SKEE 1033 51
CHAINED COMPARISONS

 Example 13 (continued):
# 5. More than two conditions in a chained comparison
temperature = 22
humidity = 65
pressure = 1010
print(15 < temperature < 30 < humidity < 70 and 1000 < pressure < 1020) # True
True

# 6. Combining integers and floating-point numbers in comparisons


score = 88.5
print(60 <= score < 90) # True, score is between 60 and 90
True

# 7. Negative number comparison


z = -10
print(-20 < z < 0) # True, -10 is between -20 and 0
True

SKEE 1033 52
CHAINED COMPARISONS

 Example 13 (continued):
# 8. Mixing comparison operators
p = 12 q = 18
print(10 < p < 15 < q < 20) # True, p is between 10 and 15, and q is between 15
and 20
True

# 9. Chained comparisons with the same variable multiple times


age = 40
print(30 < age < 50 < age + 20 < 70) # True, age is 40 and satisfies all
conditions
True

# 10. Combining logical operators and chained comparisons


n = 5
m = 10
print(1 < n < 10 and 8 < m < 12) # True, n is between 1 and 10, and m is between
8 and 12
True

SKEE 1033 53
CHAINED COMPARISONS

 Example 13 (continued):
# 11. Checking if values are within a range
gpa = 3.5
print(2.0 <= gpa <= 4.0) # True, gpa is between 2.0 and 4.0
True

# 12. Chaining with inequality signs


b = 3
print(1 < b != 2 < 4) # True, b is greater than 1, not equal to 2, less than 4
True

# 13. Float and integer mixing in chained comparisons


weight = 75.5
height = 180
print(60 < weight < 80 and 170 < height < 190) # True, weight is between 60 and
80, and height is between 170 and 190
True

# 14. Comparing variables with function calls


def get_temperature():
return 28
print(20 < get_temperature() < 30) # True, 28 is between 20 and 30
True
SKEE 1033 54
CHAINED COMPARISONS

 Example 13 (continued):
# 15. Using negative values in chained comparisons
depth = -5
print(-10 < depth < 0) # True, depth is between -10 and 0
True

# 16. Chained comparison with variables and expressions


mileage = 15000 print(10000 < mileage < 20000) # True, mileage is between 10,000
and 20,000
True

# 17. Chained comparison involving a calculated result


speed = 60
print(50 < speed < 70 and 100 < speed * 2 < 150) # False, 120 is not less than
150
True

SKEE 1033 55
CHAINED COMPARISONS

 Example 13 (continued):
# 18. Chained comparison for leap year check
year = 2024
print(1900 < year < 2100 and year % 4 == 0) # True, 2024 is between 1900 and
2100, and it's a leap year
True

# 19. Working with multiple data types


distance = 4.195 # in kilometers (marathon distance)
print(40 < distance < 45) # True, distance is between 40 and 45 kilometers
True

# 20. Chained comparison to verify a number's size


large_number = 1_000_000
print(500_000 < large_number < 2_000_000) # True, the number is between 500,000
and 2,000,000
True

SKEE 1033 56
BOOLEAN OPERATOR DRILL

Determine the following value of x before checking your answer with


python

1. x = 3>2 8. x = 0<0.5<1 15. x = (2 & ~3) | 0

2. x = 2>3 9. x = 0 < 1 < 2 16. x = (2&3) | (3>2)

3. x = -4<=-3 10. x = 1<2 or 1>4 17. x = 2 + 3 > 2

4. x = 1<1 11. x = a<2 or a>4 18. x = (3-~2==4)<2**2

5. x = 2 != 2 12. x = 1 | (0 & 1) 19. x = [Link]([1, 2])


& [Link]([1,2])
6. x = 3==3 13. x = (2 & 3) | 0
20. x = [Link]
(1, 2.2, 0.2) < 2
7. x = 4 >= 3 != 2 14. x = (~2 & 3) | 0

SKEE 1033 57

You might also like