Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

27
Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming

Transcript of Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

Page 1: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

Lecture 10 – Boolean expressions, if statements

COMPSCI 101Principles of Programming

Page 2: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 1012

Learning outcomes At the end of this lecture, students should:

be familiar with boolean values True and False be able to evaluate a boolean expression be able to use relational operators (>, <, <=, >=, !=

and ==) be able to use conditional statements (if, else)

Page 3: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 1013

Boolean expressions - conditions A condition is an expression which evaluates to

either True or False An expression which evaluates to either True or

False is called a boolean expression.

George Boole (1815-1964) invented Boolean algebra.

Page 4: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 1014

Boolean Variables Boolean variables are used to store a value which

is either: True False

Example: Naming a Boolean Variable:

Names of boolean variables express a fact that should be True or False. Good boolean variable names:

is_old_enough = True

has_passed = Truehas_won_game = True

age = Truea = True

Bad boolean variable names

Page 5: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 1015

Boolean variables We can assign one boolean variable to another

boolean variable, e.g.,

We can output the value stored in a boolean variable, e.g.,

print(has_passed)print(has_won_game)

has_passed = Truehas_won_game = has_passed

Page 6: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 1016

Relational Operators In boolean expressions, relational operators are

used to compare values The relational operators are:

==

>

<

>=

<=

!=equal to

greater than

not equal to

greater than or equal to

less than less than or equal to

Page 7: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 1017

Boolean variables Variables can be used to store the result of a

comparison, i.e., to store a boolean expressions For example:

exam_mark = 76age = 8points_so_far = 56

passed_exam = exam_mark >= 50has_won_game = points_so_far > 70

is_old_enough = age > 10is_old_enough = passed_exam != has_won_game print(passed_exam, has_won_game , is_old_enough )

True False True

DEMOExample01.p

y

Page 8: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 1018

Exercise 1 What is the output after executing the following

code?

val1 = 50val2 = 53diff = abs(val1 - val2)

print("1. ", val1 != val2)print("2. ", val1 >= val2 - 3)print("3. ", val2 % 2 == 0)print("4. ", diff < 3)

Page 9: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 1019

Boolean expressions – logical operators

As well as the relational operators, we can use the following logical operators in boolean expressions:

The three truth tables for these logical operators are shown below:

and notor

Page 10: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10110

Logical operators - examples Assume that the variable, value, has been

initialised.

value > 10 and value < 100

Is value greater than 10 and less than 100

value >= 10 or value == 5

Is value greater than or equal to 10 or is value equal to 5

not value > 8Is value not greater than 8

not (value > 8 or value == 1)

value <= 8 and value != 1

Is value not greater than 8 and not equal to 1or

Page 11: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10111

Chaining comparison operators Comparison operators can be chained. Consider the

following examples:

Note: The comparison is performed between each pair of terms to be

evaluated. For instance, in the first example, 10 < value is evaluated to True

AND value <100 is evaluated.

Is value greater than 10 and less than 100

10 < value < 100

10 < value < 20

Is value greater than 10 and less than 20

Page 12: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10112

Operator precedence Below is the priority order of operations:

Unary operators +, -

Multiplicative arithmetic

comparisons

Additive arithmetic

*, /, %

+, -

<, >, <=, >=, !=, ==

Logical not

Logical or

Logical and

not

and

or

Assignment =, +=, -=

HIGH

LOW

(Done first)

(Done last)

Exponentiation **

Page 13: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10113

Use parentheses in boolean expressions

Use parentheses to group sections of your boolean expressions to make the program more readable, e.g.,

but do not overload your boolean expressions with unnecessary parentheses, e.g.,

a > b or (a > c and b < 45)

((a > b) or ((a > c) and (b < 45)))

a > b or a > c and b < 45

“and” has a priority order Not clear!

overuse of unnecessary parentheses

Page 14: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10114

Exercise 2 What is the output after executing the following

code? def test_booleans(value): result = value > 10 or value <= 5 and value != 12 print("1.", result)

result = (value > 10 or value <= 5) and value != 12 print("2.", result)

def main(): test_booleans(12) test_booleans(13)

main()

Page 15: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10115

Logical operators – exercises 3 Assume that the variable, value, has been

initialised. Write the following four boolean expressions in Python:a) is value less than 100 or greater than 200

b) is value not equal to either 100 or 10

c) is value greater than 5 but not equal to 10

d) is value between 5 and 20 or equal to 50

Page 16: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10116

Control Structures In all the programs written so far the statements

inside functions are executed in the order in which they are written, e.g., all the statements in the main() function are executed and they are executed in sequence.

We would like to be able to control the execution of our code so that blocks of code are only executed under certain conditions. Control structures allow us to change the flow of statement execution in our programs.

Page 17: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10117

A selection statement A decision point in the program

a choice of doing something or not doing it, either do a block of code or not

alters the flow of control For example: Waterfall

Cave

Village

Birds

Choose one option or the other, but not

both.

Page 18: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10118

Python syntax for an if statement In an if statement (selection statement) the code

in the if block is executed if the condition is true

If the condition is false, then none of the statements in the block will be executed

if boolean_expression:

statement1statement2

If the condition is

true

Conditional codeIf the

condition is false

ConditionIndentation is important in Python (indicates the structure of code).• Use one tab • Be consistent with indentation

Page 19: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10119

Example What is the output after executing the following

code? Case 1:

Case 2

radius = -2if radius >= 0: area = radius * radius * math.pi print("The area of the circle of radius", radius, "is", area)

if radius >= 0: area = radius * radius * math.piprint("The area of the circle of radius", radius, "is", area)

No output!

NameError: name 'area' is not defined

Page 20: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10120

Example What is the output after executing the following

code? number = 25 if number > 30:

print("A")

if number >= 25: print("B")print("C")

number = 32 if number % 6 < 2:

print("D")

if number // 3 != 10:print("E")

BC

Page 21: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10121

Exercises What is the output after executing the following

code?

If number is 5:

If number is 6:

number = int(input("Enter an integer: "))if number % 5 == 0:

print("HiFive!")if number % 2 == 0:

print("HiEven")

Page 22: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10122

Exercise 4 What is the output after executing the following

code? a = 42b = 17c = 94 if a > b and a > c:

print("You")

if not (a > b and a > c):print("cannot")

if a > b or a > c:print("tuna")

if not(a > b or a > c):print("fish")

Page 23: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10123

If statements – a common mistake Remember that the equality operator is ==.

What is the problem with the code below?

val1 = 50val2 = 53if val1 = val2-3:

print("Unbelievable")

Note: single = is the assignment operator.

if val1 = val2-3: ^SyntaxError: invalid syntax

val1 = 50val2 = 53if val1 == val2-3:

print("Unbelievable")

Unbelievable

Page 24: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10124

Comparing float numbers Floating point numbers are always stored

approximately. It is dangerous to test doubles for equality using ==.

Test equality of floats by accepting all values within an acceptable error limit:

val1 = 0.3val2 = 0.1 * 3if val1 == val2:

print("Sigh!")if val1 != val2:

print("maybe yes, maybe no!")

maybe yes, maybe no!

val1 = 0.3val2 = 0.1 * 3error_limit = 0.00001if abs(val1 - val2) < error_limit:

print("Close enough!")

Close enough!

Page 25: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10125

Exercise: Complete the function Complete the print_message() function which

has an equal chance of printing "now", "soon" and "never". Example output to the completed program is shown below:def print_message():

def main():print("Life will improve")print_message()

main()

Life will improvenow

Life will improvesoon

Page 26: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10126

Algorithm Complete the function:

Generate a random number between 0 to 2

If the number is 0, print “now”

If the number is 1, print “soon”

If the number is 2, print “never”

Page 27: Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.

CompSci 10127

Summary In a Python program:

boolean expressions evaluate to either True or False be familiar with boolean values True and False relational operators (>, <, <=, >=, != and ==) are

used to compare values Logical operators (not, and, or) can be used to build

more complex boolean expressions if statements are used if a block of code is to be

executed only if a particular condition is True