Lecture03 DecisionStructure
Lecture03 DecisionStructure
-
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, . . . )
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
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 ?
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'
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'
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
Membership
in / not in examples
Logical Operators
Logical Operators
Examples
Logical Operators
How to know every combination?
Logical Operators can be described through Truth Tables
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
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"
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)
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
Combining Operators
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
Update
HighScore
Display
Stop HighScore
table
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
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
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
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
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
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.
elif Statement
Flowchart
Ask for a
Start
number
False
number > 0
True False
number < 0
True False
number == 0
True
Stop
Introduction to Computer Programming 29 / 36
Boolean Logic Comparison Operators Membership Logical Operators Decision Structures
elif Statement
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
elif Statement
Flowchart
Ask for a
Start
number
False
number > 0
True False
number < 0
True
Stop
elif Statement
3 if a>0:
4 print('Positive')
5 else:
6 if a<0:
7 print('Negative')
8 else:
9 print('Zero')
10
elif Statement
elif Statement
Nesting if-else-statements can become rather complex and difficult
to read.
elif Statement
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
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)
elif Statement
Exercise
Write a program to ask the user for the values of two dice rolls