Introduction to Computer Programming
-
Decision Structures
Introduction to Computer Programming 1 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Boolean Logic
History
George Boole
English Mathematician, Philosopher and
Logician in the 1800’s
Proposed that logical propositions can be
expressed by algebraic equations (AND, OR,
NOT, . . . )
This idea, now called Boolean Logic, is the
basis of Computer Science!
Introduction to Computer Programming 2 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Boolean Logic
In Python. . .
New Data type: Boolean value (bool type)
True or False
just like other values, can be assigned to variables
comparison operators return Boolean values
can be combined into expressions using logical operators
Introduction to Computer Programming 3 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Comparison Operators
Comparison operators
There are 6 comparison operators:
a == b is a equal to b ?
a != b is a different than b ?
a > b is a greater than b ?
a < b is a less than b ?
a >= b is a greater than or equal to b ?
a <= b is a less than or equal to b ?
These operators always return a bool ( True or False )
Introduction to Computer Programming 4 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Comparison Operators
Comparison operators and different Types
Example:
>>> 8 >= "four"
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
8 >= "four"
TypeError: '>=' not supported between instances of
'int' and 'str'
Numeric types can be compared (mixed numeric types int and
float are allowed)
Comparing a string with a numeric value will result in:
== will always return False
!= will always return True
< , <= , >= and > will raise a Type Error
Introduction to Computer Programming 5 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Comparison Operators
Examples
8 == 4.0
'one' == 'two'
5.1 >= 4.2
5 > 6
8.00001 != 8
"abc" == "abcd"
1 < int("12")
'a' < 'b'
'ab' < 'ac'
'Word' < 'word'
Introduction to Computer Programming 6 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Membership
Membership
An easy way to tell if an element is in a sequence
in and not in are operators that each take two arguments. They will
test the membership of an element in a collection/sequence.
A in B
returns True if A is an element in B
False otherwise
A not in B
returns True if A is not an element in B
False otherwise
Introduction to Computer Programming 7 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Membership
in / not in examples
>>> 'c' in "cat" >>> 'b' not in "cat"
True True
>>> 'r' in "cat" >>> 'a' not in "cat"
False False
>>> 'ca' in "cat" >>> 'at' not in "cat"
True False
Introduction to Computer Programming 8 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Logical Operators
What are Logical Operators?
Logical Operators are operators that combine Boolean values
these operators always return another Boolean value
these operators can be use to create complex Boolean expressions
3 Logical Operators: not , or and and
not a only one operand (to the right)
returns True if a is False
a or b two operands (one on each side)
returns True if at least one operand is True
a and b two operands (one on each side)
returns True if both operands are True
Introduction to Computer Programming 9 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Logical Operators
Examples
>>> True and False >>> not True
False False
>>> True and True >>> not not True
True True
>>> True or False >>> not (True or False)
True False
>>> (not True) and (False or True)
False
Introduction to Computer Programming 10 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Logical Operators
How to know every combination?
Logical Operators can be described through Truth Tables
Truth Table is a concise table of Boolean values that describes the
semantics of an operator
it will go through each possible combination of operands and
specify the resulting Boolean value
each row represents a combination of operands
each column represents a operand. . .
. . . with the exception of the last column which represents the
resulting value
For simplicity, we will write Truth Tables with letters:
T for True
F for False
Introduction to Computer Programming 11 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Logical Operators
Truth Table - NOT, OR and AND
a b a or b a b a and b
a not a F F F F F F
F T F T T F T F
T F T F T T F F
T T T T T T
Logical Operators precedence
If one does not use parentheses, Logical Operators are evaluated with the
following order of priority:
not
and
or
Example:
not a or not b and c ⇐⇒ (not a) or ((not b) and c)
Introduction to Computer Programming 12 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Combining Operators
Chaining Operators
Numeric/String operators can be combined with Comparison and
Logical operators to create complex Boolean expressions.
Example:
100 > 1 and -10 ** 2 <= -100 or "foo" == "foo" + "bar"
what order will the operations be evaluated in?
there is an overall order of operations that exists: a summary can be
found in the official Python 3 documentation (←click here)
what does the expression above evaluate to?
Introduction to Computer Programming 13 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Combining Operators
Summary of Operator Precedence
List of operators from highest to lowest precedence:
() parentheses are evaluated first
** exponentiation
+ and - unary + or - (sign)
* , / , // and % multiplication, division(s) and modulo
+ and - addition and substraction
== , != , < , <= , >= and > comparison operators
not
and
or
Note
Even if your expression follows operator precedence, it is good practice to
use
Introduction parentheses,
to Computer Programming at the very least, for readability 14 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Combining Operators
Exercises
Crazy one
True and True or False and True and 10 * 10 + 10 == 110 and not False
Another one
not (8 != 8) or not True
Another one
"hello" == "world" or 5 + 5 > 8 and 4 * 3 < 16 and 28 != 0
Final one
((True or False) and not True) and not (False and False)
Introduction to Computer Programming 15 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Combining Operators
Exercises
Crazy one
True and True or False and True and 10 * 10 + 10 == 110 and not False
⇒ True
Another one
not (8 != 8) or not True
⇒ True
Another one
"hello" == "world" or 5 + 5 > 8 and 4 * 3 < 16 and 28 != 0
⇒ True
Final one
((True or False) and not True) and not (False and False)
⇒ False
Introduction to Computer Programming 16 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
Combining Operators
Short Circuit Evaluation
or and and operators have particular properties
Let’s suppose unknown is a boolean variable. . .
. . . but its value is unknown
True or unknown always returns True
False and unknown always returns False
. . . whatever the value of unknown ( True / False )
Crazy example again
True and True or False and True and 10 * 10 + 10 == 110 and not False
Can be evaluated quickly with Short Circuit Evaluation
True and True or ... always returns True
Introduction to Computer Programming 17 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
if Statement
Decision structure
Until now, our programs were lists of statements executed in the order
that they appear.
This sequence structure does not allow to handle every type of task.
Examples:
a program that verifies if the user has input a number
a program that checks if the player beats high score
...
This kind of program needs decision structure
Decision structure
if Statement:
allows for conditional execution of code
allows a program to have more than one path of execution
causes one or more statements to execute only when a Boolean
Introduction to Computer Programming 18 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
if Statement
Simple decision structure
Score higher True
Start
than HighScore
False Ask user’s
name
Update
HighScore
Display
Stop HighScore
table
Introduction to Computer Programming 19 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
if Statement
if Statement Syntax
starts with keyword if
. . . followed by a boolean expression
which ends with a colon :
the code that is to be executed if the condition is met is placed in
an indented code block
once the indentation goes back one level, the body of the
if-statement ends
Example:
1 a = int(input('Type number 2:'))
2 if a == 2:
3 print("You typed")
4 print("number 2")
5 # now we're out of the if statement
6 print("outta here")
Introduction to Computer Programming 20 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
if-else Statement
else condition
In previous structures, we are executing:
one block of statements if the condition is True
. . . nothing is executed if the condition is False
We can build a program with a dual alternative decision structure with a
if-else Statement:
one block of statements if the condition is True
another block of statements is executed if the condition is False
Introduction to Computer Programming 21 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
if-else Statement
if-else flowchart
Score higher True
Start
than HighScore
False Ask user’s
name
Display
cheer-up
message Update
HighScore
Display
Stop HighScore
table
Introduction to Computer Programming 22 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
if-else Statement
if-else Statement Syntax
After the body of an if-statement. . .
go back one level of indentation to mark that the previous code
block has ended
keyword else , immediately followed by a colon :
body - indented, body ends when indentation goes back one level
(this whole else clause is totally optional; it is not required)
Example:
1 a = int(input('Type number 2:'))
2 if a == 2:
3 print("You typed number 2")
4 else:
5 print("You did not type number 2")
6 # now we're out of the if-else statement
7 print("outta here")
Introduction to Computer Programming 23 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
if-else Statement
Exercise
Write a program to ask the user for 2 numbers:
if they are equal, print a message They are the same
if they are different, print the sum and then the product
Introduction to Computer Programming 24 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
if-else Statement
Exercise
Write a program to ask the user for 2 numbers:
if they are equal, print a message They are the same
if they are different, print the sum and then the product
Possible solution:
1 a = int(input('Enter 1st number: '))
2 b = int(input('Enter 2nd number: '))
3
4 if a==b: #numbers are equal
5 print('They are the same')
6 else: #numbers are different
7 print('The sum is ' + str(a+b))
8 print('The product is ' + str(a*b))
Introduction to Computer Programming 25 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
if Statement
Chaining if-statements
Sometimes, the else condition is not enough. . .
Example:
Display a message telling that a number is whether Positive ,
Negative or Zero
A possible solution is to chain if-statements.
1 a = int(input('Enter a number: '))
2
3 if a>0:
4 print('Positive')
5 if a<0:
6 print('Negative')
7 if a==0:
8 print('Zero')
Introduction to Computer Programming 26 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
if Statement
Flowchart
Ask for a
Start
number
True
number > 0
False
Positive
True
number < 0
False Negative
True
number == 0
False
Zero
Stop
Introduction to Computer Programming 27 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
elif Statement
Nested if-else-statement
In the previous example:
if number > 0 returns True , is it necessary to check the next
conditions ( number < 0 and number == 0 )?
No, in this case only one path will be executed.
A possible solution is to nest several if-else-statements.
Introduction to Computer Programming 28 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
elif Statement
Flowchart
Ask for a
Start
number
False
number > 0
True False
number < 0
True False
number == 0
True
Positive Negative Zero
Stop
Introduction to Computer Programming 29 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
elif Statement
1 a = int(input('Enter a number: '))
2
3 if a>0:
4 print('Positive')
5 else:
6 if a<0:
7 print('Negative')
8 else:
9 if a==0:
10 print('Zero')
11
Introduction to Computer Programming 30 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
elif Statement
Flowchart
Ask for a
Start
number
False
number > 0
True False
number < 0
True
Positive Negative Zero
Stop
Introduction to Computer Programming 31 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
elif Statement
1 a = int(input('Enter a number: '))
2
3 if a>0:
4 print('Positive')
5 else:
6 if a<0:
7 print('Negative')
8 else:
9 print('Zero')
10
Introduction to Computer Programming 32 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
elif Statement
elif Statement
Nesting if-else-statements can become rather complex and difficult
to read.
Python provides a special decision structure: if-elif-else statement
elif Statement Syntax
After the body of an if -statement. . .
go back one level of indentation to mark that the previous code
block has ended
keyword elif , immediately followed by another condition and a
colon :
body - indented, body ends when indentation goes back one level
as many elif -statements as needed. . .
can still use else -statement at the end if needed
Introduction to Computer Programming 33 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
elif Statement
1 a = int(input('Enter a number: '))
2
3 if a>0: #positive?
4 print('Positive')
5 elif a<0: #negative?
6 print('Negative')
7 else: #neither positive nor negative -> zero
8 print('Zero')
9
Introduction to Computer Programming 34 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
elif Statement
elif Statement
In a if-elif-else statement:
Even if several conditions ( if or elif ) are True , only the first
corresponding body will be executed
→ order matters!
If none of the conditions is True , the else corresponding body
will be executed (if present)
Introduction to Computer Programming 35 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
elif Statement
Exercise
Write a program to ask the user for the values of two dice rolls
You have to print the name of the roll in Craps (link)
Introduction to Computer Programming 36 / 36