SlideShare a Scribd company logo
1 of 40
Mohammad Hassan
Comparison, Logical, Boolean, Bitwise Operators
• Comparison operators
• Boolean operators
• To understand the order of operations
• Written programs vs Python interpreter
Objectives
Control of program flow
Program flow is controlled by using both Conditional
operators and Logical operators
Comparison operators
Numerical comparison operators are also known as
Conditional operators. Normally they are used to
compare two values to see whether they are equal or one
value is greater or less than the other value, then the
program decides what actions to take, e.g. whether to
execute a program or terminate the program.
Logical operators
These are operators that allow a program to make a
decision based on multiple conditions. Each operand is
considered a condition that can be evaluated to be a true
or false value. Then the value of the conditions is used to
determine the overall value of the op1 operator op2 or
!op1 or both.
Comparison/selection/decision
statements
It sometimes becomes necessary when processing data to
compare the value of a variable to the value of another
variable, or to compare the value of a variable to that of a
constant.
The following relational operators are used to make such
comparisons.
A condition is an expression that when evaluated gives
either a TRUE or a FALSE. This expression is called a
Boolean expression. These conditions use the relational
operators between two variables, or between a variable
and a constant.
Boolean operators
When selection is based upon one or more
expressions/decisions being TRUE or FALSE, it is
possible to combine the expressions/decisions together
using the Boolean operators AND or OR.
If the AND operator is used, both conditions must be met
in order for the total expression to be true.
If the OR operator is used, either condition must be met in
order for the total expression to be true.
Comparison Operators
Overview
Comparison operators
Relational operators
Equality operators
 Are all the same thing
Include things like >, >=, <, <=, ==, !=
Comparison Operators
Always return a Boolean result
 True or False
 Indicates whether a relationship holds
between their operands
operands
a >= b
comparison operator
Comparison Examples
What are the following comparisons asking?
a >= b
 Is a greater than or equal to b?
a == b
 Is a equivalent to b?
Equality operator
Question: are two values equal?
To ask this question, you use the == (equal equal) operator
The == (equal to) operator compares the values of two operands. If they are equal,
the result of the comparison is True. If they are not equal, the result of the
comparison is False.
It is a binary operator with left-sided binding. It needs two arguments
and checks if they are equal.
var = 0 # Assigning 0 to var
print(var == 0)
var = 1 # Assigning 1 to var
print(var == 0)
Inequality: the not equal to operator (!=)
The != (not equal to) operator compares the values of
two operands, too. Here is the difference: if they are
equal, the result of the comparison is False. If they are
not equal, the result of the comparison is True.
var = 0 # Assigning 0 to var
print(var != 0)
var = 1 # Assigning 1 to var
print(var != 0)
Comparison Operators in Python
Operator Meaning
< Less than (exclusive)
<= Less than or equal to
(inclusive)
> Greater than (exclusive)
>= Greater than or equal to
(inclusive)
== Equivalent to
!= Not equivalent to
Comparison Examples (Continued)
What do these evaluate to if
a = 10 and b = 20?
a == b
 Is a equivalent to b?
 Is 10 equivalent to 20?
 False
Comparison Examples (Continued)
What do these evaluate to if
a = 10 and b = 20?
a <= b
 Is a less than or equal to b?
 Is 10 less than or equal to 20?
 True
Comparison vs Assignment
A common mistake is to use the assignment operator (=)
in place of the relational (==)
This is a very common mistake to make!
= is an assignment operator, e.g., a =
b assigns a with the value of b;
== is the question are these values equal? so a ==
b compares a and b;
This type of mistake will trigger an error in Python, but
you may still make it on paper!
Equals vs Equivalence
What does a = b do?
Assigns a the value stored in b
Changes a’s value to the value of b
What does a == b do?
Checks if a is equivalent to b
Does not change the value of a or b
Evaluating to Boolean Values
Comparison Operators and
Simple Data Types
Examples:
8 < 15 evaluates to
6 != 6 evaluates to
2.5 > 5.8 evaluates to
4.0 == 4 evaluates to
True
False
False
True
“Value” of Boolean Variables
When we discuss Boolean outputs, we use
True and False
We can also think of it in terms of
1 and 0
True = 1
False = 0
“Value” of Boolean Variables
Other data types can also be seen as
“True” or “False” in Python
Anything empty or zero is False
 "" (empty string), 0, 0.0
Everything else is True
 81.3, 77, -5, "zero", 0.01
 Even "0" and "False" evaluate to True
Making use of the answers
What can you do with the answer (i.e., the result of a
comparison operation) you get from the computer?
There are at least two possibilities: first, you can memorize
it (store it in a variable) and make use of it later. How do
you do that? Well, you use an arbitrary variable like this:
answer = number_of_lions >= number_of_lionesses
The content of the variable will tell you the answer to the
question asked.
The second possibility is more convenient and far more
common: you can use the answer you get to make a
decision about the future of the program.
You need a special instruction for this purpose.
Logical Operators
Logical Operators
If we have some free time, and the weather is good, we will go for a
walk.
We've used the conjunction and, which means that going for a walk
depends on the simultaneous fulfilment of these two conditions. In
the language of logic, such a connection of conditions is called
a conjunction. And now another example:
If you are in the mall or I am in the mall, one of us will buy a gift for
Mom.
The appearance of the word or means that the purchase depends on
at least one of these conditions. In logic, such a compound is called
a disjunction.
Python has operators to build conjunctions and disjunctions. Without
them, the expressive power of the language would be substantially
weakened. They're called logical operators.
Logical Operators
Sometimes also called Boolean operators
There are three logical operators:
 and
 or
 not
They let us build complex Boolean expressions
By combining simpler Boolean
expressions
Logical Operators – and
One logical conjunction operator in Python is the word and.
It's a binary operator with a priority that is lower than
the one expressed by the comparison operators. It
allows us to code complex conditions without the use of
parentheses like this one:
counter > 0 and value == 100
Let’s evaluate this expression, bool1 = a and b
For a and b to be True, both a and b must be true
Value of a Value of b Value of
bool1
True True True
True False False
False True False
False False False
Practice with and
a = 10
b = 20
c = 30
ex1 = a < b
ex2 = a < b and b < c
ex3 = (a + b == c) and (b – 10 == a) 
and (c / 3 == a)
print (ex1, ex2, ex3)
output:
True True True
Logical Operators – or
A disjunction operator is the word or. It's a binary operator
with a lower priority than and (just like + compared to *).
Its truth table is as follows:
Let’s evaluate this expression
bool2 = a or b
For a or b to be True, either a or b must be true
Value of a Value of b Value of
bool2
True True True
True False True
False True True
False False False
Logical Operators – not
Let’s evaluate this expression
bool3 = not a
not a calculates the Boolean value of a and returns the
opposite of that
Value of a Value of
bool3
True False
False True
It's a unary operator performing a logical negation. Its
operation is simple: it turns truth into falsehood and
falsehood into truth.
This operator is written as the word not, and its priority is
very high: the same as the unary + and -. Its truth table is
simple:
Complex Expressions
We can put multiple operators together!
bool4 = a and (b or c)
What does Python do first?
 Computes (b or c)
 Then computes a and the result
Practice with Comparisons
a = 10
b = 20
c = 30
bool1 = True and (a > b)
bool2 = (not True) or (b != c)
bool3 = (True and (not False)) or (a > b)
bool4 = (a % b == 2) and ((not True) or False)
print (bool1, bool2, bool3, bool4)
output:
False True False
True
Priority table (updated)
Priority Operator
1 +, - unary
2 **
3 *, /, //, %
4 +, - binary
5 <, <=, >, >=
6 ==, !=
7 not
8 and
9 or
Logical values vs. single bits
Logical operators take their arguments as a whole regardless of how many bits
they contain. The operators are aware only of the value: zero (when all the bits
are reset) means False; not zero (when at least one bit is set) means True.
The result of their operations is one of these values: False or True. This means
that this snippet will assign the value True to the j variable if i is not zero;
otherwise, it will be False.
i = 1
j = not not i
In Python, the "not" keyword is used to perform logical negation, meaning it will
invert a Boolean value.
In this case, the variable "i" is assigned the value of 1, which is equivalent to
True in Python. Therefore, when the "not" operator is applied to i, it will invert its
value to False.
Applying the "not" operator again will invert the value of False, which will result
in True.
Therefore, the variable "j" will be assigned the value True.
Bitwise operators
There are four operators that allow you to manipulate
single bits of data. They are called bitwise operators.
They cover all the operations we mentioned before in
the logical context, and one additional operator. This is
the xor (as in exclusive or) operator, and is denoted
as ^ (caret).
Here are all of them:
•& (ampersand) ‒ bitwise conjunction;
•| (bar) ‒ bitwise disjunction;
•~ (tilde) ‒ bitwise negation;
Bitwise operators
Bitwise operations (&, |, and ^)
Argument A Argument B A & B A | B A ^ B
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Bitwise operations (~)
Argument ~ Argument
0 1
1 0
Let's make it easier:
•& requires exactly two 1s
to provide 1 as the result;
•| requires at least one 1 to
provide 1 as the result;
•^ requires exactly
one 1 to provide 1 as the
result.
Bitwise operators
The arguments of these operators must be integers; we
must not use floats here.
The difference in the operation of the logical and bit
operators is important: the logical operators do not
penetrate into the bit level of its argument. They're only
interested in the final integer value.
Bitwise operators are stricter: they deal with every bit
separately. If we assume that the integer variable occupies
64 bits (which is common in modern computer systems), you
can imagine the bitwise operation as a 64-fold evaluation of
the logical operator for each pair of bits of the arguments.
This analogy is obviously imperfect, as in the real world all
these 64 operations are performed at the same time
(simultaneously).
Logical vs. bit operations
We'll now show you an example of the difference in
operation between the logic and bit operations. Let's
assume that the following assignments have been
performed:
Logical operation:
Bitwise operation:
log = i and j
log: True
Variable Integer Stored with 32 bits
i 15 00000000000000000000000000001111
j 22 00000000000000000000000000010110
Variable Integer Stored with 32 bits
i 15 00000000000000000000000000001111
j 22 00000000000000000000000000010110
bit = i & j
00000000000
00000000000
0000000110
=>6
Logical vs. bit operations
i = 15
j = 22
logneg = not i
The logneg variable will be set to False ‒ nothing more
needs to be done.&
bitneg = ~I
i 00000000000000000000000000001111
bitneg = ~i 11111111111111111111111111110000
Logical vs. bit operations
x = x & y x &= y
x = x | y x |= y
x = x ^ y x ^= y
Each of these two-argument operators can be used
in abbreviated form. These are the examples of their
equivalent notations:

More Related Content

Similar to Lecture 07.pptx

C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)jahanullah
 
Data types and operators in vb
Data types and operators  in vbData types and operators  in vb
Data types and operators in vballdesign
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3dplunkett
 
GE3151 PSPP UNIT III QUESTION BANK.docx.pdf
GE3151 PSPP UNIT III QUESTION BANK.docx.pdfGE3151 PSPP UNIT III QUESTION BANK.docx.pdf
GE3151 PSPP UNIT III QUESTION BANK.docx.pdfAsst.prof M.Gokilavani
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statementsİbrahim Kürce
 
UNIT - 2 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT - 2 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHONUNIT - 2 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT - 2 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHONNandakumar P
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)It Academy
 
python operators.ppt
python operators.pptpython operators.ppt
python operators.pptErnieAcuna
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unitmichaelaaron25322
 
Operators
OperatorsOperators
OperatorsKamran
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++Neeru Mittal
 

Similar to Lecture 07.pptx (20)

Py-Slides-2 (1).ppt
Py-Slides-2 (1).pptPy-Slides-2 (1).ppt
Py-Slides-2 (1).ppt
 
Py-Slides-2.ppt
Py-Slides-2.pptPy-Slides-2.ppt
Py-Slides-2.ppt
 
Py-Slides-2.ppt
Py-Slides-2.pptPy-Slides-2.ppt
Py-Slides-2.ppt
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
Operators
OperatorsOperators
Operators
 
Data types and operators in vb
Data types and operators  in vbData types and operators  in vb
Data types and operators in vb
 
Java script session 4
Java script session 4Java script session 4
Java script session 4
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3
 
GE3151 PSPP UNIT III QUESTION BANK.docx.pdf
GE3151 PSPP UNIT III QUESTION BANK.docx.pdfGE3151 PSPP UNIT III QUESTION BANK.docx.pdf
GE3151 PSPP UNIT III QUESTION BANK.docx.pdf
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
 
UNIT - 2 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT - 2 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHONUNIT - 2 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT - 2 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
 
python operators.ppt
python operators.pptpython operators.ppt
python operators.ppt
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unit
 
MODULE_2_Operators.pptx
MODULE_2_Operators.pptxMODULE_2_Operators.pptx
MODULE_2_Operators.pptx
 
slides03.ppt
slides03.pptslides03.ppt
slides03.ppt
 
Operators
OperatorsOperators
Operators
 
Python Keywords
Python KeywordsPython Keywords
Python Keywords
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 

Recently uploaded

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 

Recently uploaded (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 

Lecture 07.pptx

  • 1. Mohammad Hassan Comparison, Logical, Boolean, Bitwise Operators
  • 2. • Comparison operators • Boolean operators • To understand the order of operations • Written programs vs Python interpreter Objectives
  • 3. Control of program flow Program flow is controlled by using both Conditional operators and Logical operators
  • 4. Comparison operators Numerical comparison operators are also known as Conditional operators. Normally they are used to compare two values to see whether they are equal or one value is greater or less than the other value, then the program decides what actions to take, e.g. whether to execute a program or terminate the program.
  • 5. Logical operators These are operators that allow a program to make a decision based on multiple conditions. Each operand is considered a condition that can be evaluated to be a true or false value. Then the value of the conditions is used to determine the overall value of the op1 operator op2 or !op1 or both.
  • 6. Comparison/selection/decision statements It sometimes becomes necessary when processing data to compare the value of a variable to the value of another variable, or to compare the value of a variable to that of a constant. The following relational operators are used to make such comparisons. A condition is an expression that when evaluated gives either a TRUE or a FALSE. This expression is called a Boolean expression. These conditions use the relational operators between two variables, or between a variable and a constant.
  • 7. Boolean operators When selection is based upon one or more expressions/decisions being TRUE or FALSE, it is possible to combine the expressions/decisions together using the Boolean operators AND or OR. If the AND operator is used, both conditions must be met in order for the total expression to be true. If the OR operator is used, either condition must be met in order for the total expression to be true.
  • 9. Overview Comparison operators Relational operators Equality operators  Are all the same thing Include things like >, >=, <, <=, ==, !=
  • 10. Comparison Operators Always return a Boolean result  True or False  Indicates whether a relationship holds between their operands operands a >= b comparison operator
  • 11. Comparison Examples What are the following comparisons asking? a >= b  Is a greater than or equal to b? a == b  Is a equivalent to b?
  • 12. Equality operator Question: are two values equal? To ask this question, you use the == (equal equal) operator The == (equal to) operator compares the values of two operands. If they are equal, the result of the comparison is True. If they are not equal, the result of the comparison is False. It is a binary operator with left-sided binding. It needs two arguments and checks if they are equal. var = 0 # Assigning 0 to var print(var == 0) var = 1 # Assigning 1 to var print(var == 0)
  • 13. Inequality: the not equal to operator (!=) The != (not equal to) operator compares the values of two operands, too. Here is the difference: if they are equal, the result of the comparison is False. If they are not equal, the result of the comparison is True. var = 0 # Assigning 0 to var print(var != 0) var = 1 # Assigning 1 to var print(var != 0)
  • 14. Comparison Operators in Python Operator Meaning < Less than (exclusive) <= Less than or equal to (inclusive) > Greater than (exclusive) >= Greater than or equal to (inclusive) == Equivalent to != Not equivalent to
  • 15. Comparison Examples (Continued) What do these evaluate to if a = 10 and b = 20? a == b  Is a equivalent to b?  Is 10 equivalent to 20?  False
  • 16. Comparison Examples (Continued) What do these evaluate to if a = 10 and b = 20? a <= b  Is a less than or equal to b?  Is 10 less than or equal to 20?  True
  • 17. Comparison vs Assignment A common mistake is to use the assignment operator (=) in place of the relational (==) This is a very common mistake to make! = is an assignment operator, e.g., a = b assigns a with the value of b; == is the question are these values equal? so a == b compares a and b; This type of mistake will trigger an error in Python, but you may still make it on paper!
  • 18. Equals vs Equivalence What does a = b do? Assigns a the value stored in b Changes a’s value to the value of b What does a == b do? Checks if a is equivalent to b Does not change the value of a or b
  • 20. Comparison Operators and Simple Data Types Examples: 8 < 15 evaluates to 6 != 6 evaluates to 2.5 > 5.8 evaluates to 4.0 == 4 evaluates to True False False True
  • 21. “Value” of Boolean Variables When we discuss Boolean outputs, we use True and False We can also think of it in terms of 1 and 0 True = 1 False = 0
  • 22. “Value” of Boolean Variables Other data types can also be seen as “True” or “False” in Python Anything empty or zero is False  "" (empty string), 0, 0.0 Everything else is True  81.3, 77, -5, "zero", 0.01  Even "0" and "False" evaluate to True
  • 23. Making use of the answers What can you do with the answer (i.e., the result of a comparison operation) you get from the computer? There are at least two possibilities: first, you can memorize it (store it in a variable) and make use of it later. How do you do that? Well, you use an arbitrary variable like this: answer = number_of_lions >= number_of_lionesses The content of the variable will tell you the answer to the question asked. The second possibility is more convenient and far more common: you can use the answer you get to make a decision about the future of the program. You need a special instruction for this purpose.
  • 25. Logical Operators If we have some free time, and the weather is good, we will go for a walk. We've used the conjunction and, which means that going for a walk depends on the simultaneous fulfilment of these two conditions. In the language of logic, such a connection of conditions is called a conjunction. And now another example: If you are in the mall or I am in the mall, one of us will buy a gift for Mom. The appearance of the word or means that the purchase depends on at least one of these conditions. In logic, such a compound is called a disjunction. Python has operators to build conjunctions and disjunctions. Without them, the expressive power of the language would be substantially weakened. They're called logical operators.
  • 26. Logical Operators Sometimes also called Boolean operators There are three logical operators:  and  or  not They let us build complex Boolean expressions By combining simpler Boolean expressions
  • 27. Logical Operators – and One logical conjunction operator in Python is the word and. It's a binary operator with a priority that is lower than the one expressed by the comparison operators. It allows us to code complex conditions without the use of parentheses like this one: counter > 0 and value == 100 Let’s evaluate this expression, bool1 = a and b For a and b to be True, both a and b must be true Value of a Value of b Value of bool1 True True True True False False False True False False False False
  • 28. Practice with and a = 10 b = 20 c = 30 ex1 = a < b ex2 = a < b and b < c ex3 = (a + b == c) and (b – 10 == a) and (c / 3 == a) print (ex1, ex2, ex3) output: True True True
  • 29. Logical Operators – or A disjunction operator is the word or. It's a binary operator with a lower priority than and (just like + compared to *). Its truth table is as follows: Let’s evaluate this expression bool2 = a or b For a or b to be True, either a or b must be true Value of a Value of b Value of bool2 True True True True False True False True True False False False
  • 30. Logical Operators – not Let’s evaluate this expression bool3 = not a not a calculates the Boolean value of a and returns the opposite of that Value of a Value of bool3 True False False True It's a unary operator performing a logical negation. Its operation is simple: it turns truth into falsehood and falsehood into truth. This operator is written as the word not, and its priority is very high: the same as the unary + and -. Its truth table is simple:
  • 31. Complex Expressions We can put multiple operators together! bool4 = a and (b or c) What does Python do first?  Computes (b or c)  Then computes a and the result
  • 32. Practice with Comparisons a = 10 b = 20 c = 30 bool1 = True and (a > b) bool2 = (not True) or (b != c) bool3 = (True and (not False)) or (a > b) bool4 = (a % b == 2) and ((not True) or False) print (bool1, bool2, bool3, bool4) output: False True False True
  • 33. Priority table (updated) Priority Operator 1 +, - unary 2 ** 3 *, /, //, % 4 +, - binary 5 <, <=, >, >= 6 ==, != 7 not 8 and 9 or
  • 34. Logical values vs. single bits Logical operators take their arguments as a whole regardless of how many bits they contain. The operators are aware only of the value: zero (when all the bits are reset) means False; not zero (when at least one bit is set) means True. The result of their operations is one of these values: False or True. This means that this snippet will assign the value True to the j variable if i is not zero; otherwise, it will be False. i = 1 j = not not i In Python, the "not" keyword is used to perform logical negation, meaning it will invert a Boolean value. In this case, the variable "i" is assigned the value of 1, which is equivalent to True in Python. Therefore, when the "not" operator is applied to i, it will invert its value to False. Applying the "not" operator again will invert the value of False, which will result in True. Therefore, the variable "j" will be assigned the value True.
  • 35. Bitwise operators There are four operators that allow you to manipulate single bits of data. They are called bitwise operators. They cover all the operations we mentioned before in the logical context, and one additional operator. This is the xor (as in exclusive or) operator, and is denoted as ^ (caret). Here are all of them: •& (ampersand) ‒ bitwise conjunction; •| (bar) ‒ bitwise disjunction; •~ (tilde) ‒ bitwise negation;
  • 36. Bitwise operators Bitwise operations (&, |, and ^) Argument A Argument B A & B A | B A ^ B 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 Bitwise operations (~) Argument ~ Argument 0 1 1 0 Let's make it easier: •& requires exactly two 1s to provide 1 as the result; •| requires at least one 1 to provide 1 as the result; •^ requires exactly one 1 to provide 1 as the result.
  • 37. Bitwise operators The arguments of these operators must be integers; we must not use floats here. The difference in the operation of the logical and bit operators is important: the logical operators do not penetrate into the bit level of its argument. They're only interested in the final integer value. Bitwise operators are stricter: they deal with every bit separately. If we assume that the integer variable occupies 64 bits (which is common in modern computer systems), you can imagine the bitwise operation as a 64-fold evaluation of the logical operator for each pair of bits of the arguments. This analogy is obviously imperfect, as in the real world all these 64 operations are performed at the same time (simultaneously).
  • 38. Logical vs. bit operations We'll now show you an example of the difference in operation between the logic and bit operations. Let's assume that the following assignments have been performed: Logical operation: Bitwise operation: log = i and j log: True Variable Integer Stored with 32 bits i 15 00000000000000000000000000001111 j 22 00000000000000000000000000010110 Variable Integer Stored with 32 bits i 15 00000000000000000000000000001111 j 22 00000000000000000000000000010110 bit = i & j 00000000000 00000000000 0000000110 =>6
  • 39. Logical vs. bit operations i = 15 j = 22 logneg = not i The logneg variable will be set to False ‒ nothing more needs to be done.& bitneg = ~I i 00000000000000000000000000001111 bitneg = ~i 11111111111111111111111111110000
  • 40. Logical vs. bit operations x = x & y x &= y x = x | y x |= y x = x ^ y x ^= y Each of these two-argument operators can be used in abbreviated form. These are the examples of their equivalent notations:

Editor's Notes

  1. Instructions To create em dash above headline Same size and weight as the headline and set using a soft return. PC: Em dash (—): Alt+Ctrl+ - (minus) Mac: Em dash (—): Shift+Alt/Option+hyphen