0% found this document useful (0 votes)
0 views

04 - Boolean Logic and Decision Structures

The document outlines the course COMP 125 - Programming with Python, focusing on Boolean logic and decision structures. It covers Boolean variables, relational and logical operators, control structures, and conditional statements, providing examples and exercises for practical understanding. Additionally, it includes a disclaimer regarding the use of course materials and the legal implications of unauthorized sharing.

Uploaded by

Abdul Moeez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

04 - Boolean Logic and Decision Structures

The document outlines the course COMP 125 - Programming with Python, focusing on Boolean logic and decision structures. It covers Boolean variables, relational and logical operators, control structures, and conditional statements, providing examples and exercises for practical understanding. Additionally, it includes a disclaimer regarding the use of course materials and the legal implications of unauthorized sharing.

Uploaded by

Abdul Moeez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

04 – Boolean Logic and Decision Structures

COMP 125 – Programming with Python


Recording Disclaimer

The synchronous sessions are recorded (audiovisual recordings). The students are not required to keep their
cameras on during class.

The audiovisual recordings, presentations, readings and any other works offered as the course materials aim
to support remote and online learning. They are only for the personal use of the students. Further use of
course materials other than the personal and educational purposes as defined in this disclaimer, such as
making copies, reproductions, replications, submission and sharing on different platforms including the digital
ones or commercial usages are strictly prohibited and illegal.

The persons violating the above-mentioned prohibitions can be subject to the administrative, civil, and
criminal sanctions under the Law on Higher Education Nr. 2547, the By-Law on Disciplinary Matters of Higher
Education Students, the Law on Intellectual Property Nr. 5846, the Criminal Law Nr. 5237, the Law on
Obligations Nr. 6098, and any other relevant legislation.

The academic expressions, views, and discussions in the course materials including the audio-visual
recordings fall within the scope of the freedom of science and art.

COMP 125 Programming with Python 2


Boolean Expressions
§ Boolean variable can reference one of the two values, either True or False
§ Boolean variables are mostly used as flags
§ True, if the condition does exist
§ False, if the condition does not exist
§ e.g., graduated = False (if you did not graduate yet)
§ e.g., visited = True (if you already visited a particular city)

§ Boolean expression is an expression whose value is either True or False


§ Relational and logical (Boolean) operators are used to form Boolean
expressions

COMP 125 Programming with Python 3


Relational Operators

Relational operators Booelan expressions using relational operators


Operator Meaning Expression Meaning

> Greater than x > y Is x greater than y?


< Less than x < y Is x less than y?
>= Greater than or equal to x >= y Is x greater than or equal to y?
<= Less than or equal to x <= y Is x less than or equal to y?
== Equal to x == y Is x equal to y?
!= Not equal to x != y Is x not equal to y?

COMP 125 Programming with Python 4


Relational Operators

§ Do not confuse = with ==


§ = is the assignment operator
§ == is the equality operator that checks if two of its operands are equal to each other

Assign 5 to x
Assign 5 to y

Check : Is x equal to y?
Output : True

Assign 4 to z

Check : Is x equal to z?
Output : False

COMP 125 Programming with Python 5


Comparing Strings

§ Relational operators are also defined on the


string data type
§ They compare the Unicode characters of the string
from the zeroth index till the end
§ Comparison is case-sensitive

COMP 125 Programming with Python 6


Logical (Boolean) Operators
§ and and or binary operators connect two Boolean expressions into one
compound expression
§ not is a unary operator that negates a Boolean expression

Logical Operators
Operator Meaning
If both operands must be True for the compound expression to be
and
True
or If any of the operands is True then the compound expression is True
Reverses the logical value of the operand. If the operand is True then
not the operator returns False. If the operand is False then the operator
returns True.

COMP 125 Programming with Python 7


Compound Boolean expressions

Compound Boolean expressions using logical operators


Expression Meaning
x > y and a < b Is x greater than y AND is a less than b?
x == y or x == z Is x equal to y OR is x equal to z?
not (x > y) Is the expression x > y NOT true?

COMP 125 Programming with Python 8


Truth Tables

X Y X or Y X and Y X not X
False False False False False True
False True True False True False
True False True False
True True True True

COMP 125 Programming with Python 9


Truth Value Testing
§ Any object can be tested for its truth value
§ It is the value when it is converted to the Boolean
data type using bool(), remember the previous
class
§ The following have the truth value of False
§ Constants: False, None
§ Zero of any numeric type: 0, 0.0, 0j
§ Empty sequences and collections: "", '', [], {}, (), set(),
range(0)
§ The following have the truth value of True
§ Constant: True
§ Numeric values that are not equal to zero
§ Non-empty sequences or collections (lists, tuples,
strings, dictionaries, sets)

COMP 125 Programming with Python 10


Lazy Evaluation
§ Python evaluates the binary logical operators as follows
§ It always evaluates the first operand (X)
§ X and Y
§ if the truth value of X is False, it returns the value of X
§ otherwise, it returns the value of Y
§ X or Y
§ if the truth value of X is True, it returns the value of X
§ otherwise, it returns the value of Y
This way of evaluation is sometimes important, e.g., what is the output of the following program when
the user enters 0 as the input?

COMP 125 Programming with Python 11


Combining Logical Operators
§ Python’s logical operators have lower precedence when compared with
other operators
§ Precedence of the logical operators from high to low:
§ not
§ and
§ or

§ Consider using parentheses to make the code more readable

COMP 125 Programming with Python 12


Exercise

§ What is the output of this code fragment?

Precedence of the logical operators


from high to low
not
and
or

COMP 125 Programming with Python 13


Control Structures

§ There are three types of control structures


§ Sequence statements, which are executed sequentially
§ Conditional (decision) statements: if, if-else, if-elif-else
§ Repetition statements: for, while
§ These statements are combined by either sequencing or nesting

COMP 125 Programming with Python 14


Sequence Statements
§ They are executed sequentially
1st line
§ Their execution does not depend
The following
on any condition; they are always message will
executed and in the same order appear in the Enter your first name
console. and press ENTER

2nd line

Enter your last name


and press ENTER

3rd line

COMP 125 Programming with Python 15


Conditional Statements

§ A specific action is performed only if a certain condition exists (i.e., if a


certain condition is True)

Cold True
outside?
It is said that the action
Wear a coat
False is 'conditionally executed'

COMP 125 Programming with Python 16


if statement
§ We use the if statement to write a single alternative decision structure

expression that will be evaluated


as True or False

True colon is
Condition required

if code block
False block of
statements
indentation is required

COMP 125 Programming with Python 17


Example
§ Kate teaches a science class and her students are required to take three tests. She wants
to write a program that her students can use to calculate their average test score. She
also wants the program to congratulate the student if the average is greater than or
equal 80.

Pseudocode
Get the first test score
Get the second test score
sequential
Get the third test score statement
(last lecture)
Calculate their average (their sum divided by 3)
Display the average
conditional
If the average is greater than or equal to 80
statement
Display the congratulation message (new part)

COMP 125 Programming with Python 18


if-else statement
§ We use the if-else statement to write a dual alternative
decision structure

True
condition

False if code block

else code block

COMP 125 Programming with Python 19


if-else statement

1 1
if condition1: Check condition1 if condition1: Check condition1
statement If True execute this block and statement If False ignore this block and
statement 2 ignore the rest of the structure statement execute the else block
… …
else: else:
statement statement
statement statement 2
… …

Control jumps here to the statement Control jumps here to the statement
3 following the if-else statement 3 following the if-else statement

COMP 125 Programming with Python 20


if-else statement

if temperature < 0:
print(‘Cold’)
Align if and else statements print(‘Turn up the heat!’) The statements in each
else: blockmust be
print(‘Warm’) consistently indented
print(‘Pass the sunscreen’)

Important rules:
§ if clause and else clause must be aligned
§ The statements following the if clause and else clause must be consistently indented

COMP 125 Programming with Python 21


Example

§ June 10, 1960, is called a special 6/10/60


date because when it is written in the
6 * 10 = 60
following format, the month times the
day equals the year

§ Design a program that asks the user to


enter a month (in numeric form), a day,
and a two-digit year, and displays
whether it is special. You may assume
that all inputs entered by the user are
valid.

COMP 125 Programming with Python 22


Example
§ Suppose a salesperson has a quota of $50000
§ The sales variable references the amount s/he has sold
§ Check whether the quota has been met

CASE SENSITIVE!!
DO NOT USE
true - false
Capitalize the first letter

SAME

COMP 125 Programming with Python 23


Overall…

if randombool == True: if randombool:


SAME
statement statement

if randombool == False: if not randombool:


SAME
statement statement

COMP 125 Programming with Python 24


Exercise

§ Write a program that reads three floating point


numbers and displays their minimum and
maximum

COMP 125 Programming with Python 25


Nested Conditional Statements

§ You write an if (or if-else) statement in the statement block of another if (or else)
§ They are used to test more than one condition

COMP 125 Programming with Python 26


Example
§ Write a program that determines whether a bank customer qualifies for a loan. To
qualify the applicant must be working at the current job for more than two years
and have a salary greater than $30,000. The program should display why when
the customer doesn’t qualify.

Indentation is used to match the if and else clauses

COMP 125 Programming with Python 27


Exercise

§ Write a program that asks the user to enter an integer, and displays whether it is zero, a
positive number, or a negative number

COMP 125 Programming with Python 28


if-elif-else statement
1
1
if condition1: Check condition1 if condition1: Check condition1
statement If False ignore this block
statement If True execute this block and
2 statement
statement ignore the rest of the structure
… … 2
elif condition2: Check condition2
elif condition2:
statement statement If True execute this block and
statement 3
statement ignore the rest of the structure
… …
elif condition3: elif condition3:
statement
statement
statement statement


else: else:
statement statement
statement
statement
… …

Control jumps here to the statement Control jumps here to the statement
3 following the if-else statement 4 following the if-else statement

COMP 125 Programming with Python 29


Exercise (revisited)

§ Write a program that asks the user to enter an integer, and displays whether it is zero, a
positive number, or a negative number

COMP 125 Programming with Python 30


Exercise

§ Write a program that takes a grade, converts


it to a letter equivalent according to the
following rules, and displays the letter grade
on the screen
§ A : 90 ≤ grade ≤ 100
§ B : 80 ≤ grade ≤ 89
§ C : 70 ≤ grade ≤ 79
§ D : 60 ≤ grade ≤ 69
§ F : 0 ≤ grade ≤ 59
§ Invalid: All other grades
Can you write another version of this algorithm
that calculates the letter grade only using the
equality operator?

COMP 125 Programming with Python 31


Exercise

§ Write a program that takes a grade, converts


it to a letter equivalent according to the
following rules, and displays the letter grade
on the screen
§ A : 90 ≤ grade ≤ 100
§ B : 80 ≤ grade ≤ 89
§ C : 70 ≤ grade ≤ 79
§ D : 60 ≤ grade ≤ 69
§ F : 0 ≤ grade ≤ 59
§ Invalid: All other grades

Remember the integer division operator //

COMP 125 Programming with Python 32


Exercise
§ Implement a unit converter that takes a value in
centimeters and one of the following unit
options, converts it to the unit of interest, and
displays the equivalent value. You may assume
that all inputs are valid.
§ mm, millimeter (1cm = 10mm)
§ cm, centimeter
§ m, meter (1m = 100cm)
§ in, inch (1in = 2.54cm)

COMP 125 Programming with Python 33


Excercise
§ What is the output of the following program for different values of N?

N Output
0
-10 C EXAMPLE
0

100
90 A
50

101
91 D
E
0
-10
-20 B
-20
Excercise
§ What is the output of the following program for different values of N?

N Output

hello
4 40

16 100

comp 125
15 10

50 500
505

COMP 125 Programming with Python 35

You might also like