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

Slides:



Advertisements
Similar presentations
Decision Structures - If / Else If / Else. Decisions Often we need to make decisions based on information that we receive. Often we need to make decisions.
Advertisements

Conditional Execution
Making Decisions in Python Sec 9-10 Web Design. Objectives The student will: Understand how to make a decision in Python Understand the structure of an.
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Python Programming Language
COMPSCI 101 Principles of Programming Lecture 6 – Getting user input, converting between types, generating random numbers.
Control Structures Control structures are used to manage the order in which statements in computer programs will be executed Three different approaches.
Conditional Statements Introduction to Computing Science and Programming I.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
1 9/24/07CS150 Introduction to Computer Science 1 Relational Operators and the If Statement.
Basic Elements of Programming A VB program is built from statements, statements from expressions, expressions from operators and operands, and operands.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
Flow control 1: if-statements (Liang 72-80) if(radius < 0) { System.out.println(“cannot get area: radius below zero”); } else { double area = radius *
1 CS150 Introduction to Computer Science 1 Relational Operators and the If Statement 9/22/08.
Introduction to Python and programming Michael Ernst UW CSE 190p Summer 2012.
Lecture 11 – if … else, if... elif statements, nested ifs COMPSCI 1 1 Principles of Programming.
Lecture 2 - Variables, program execution, calculations, print() COMPSCI 101 Principles of Programming.
CSci 125 Lecture 10 Martin van Bommel. Simple Statements Expression followed by semicolon Assignments total = n1 + n2; Function calls printf(”Hello.\n”);
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Decision Structures and Boolean Logic
Branching and Conditions CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Python – Making Decisions Lecture 02. Control Structures A program that only has one flow is useful but limited. We can use if statements to make these.
Lecture 20 – Test revision COMPSCI 101 Principles of Programming.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Lecture Set 5 Control Structures Part A - Decisions Structures.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Computer Science 111 Fundamentals of Programming I Making Choices with if Statements.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
CPS120: Introduction to Computer Science Operations Lecture 9.
Decisions in Python Bools and simple if statements.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Introduction to Python and programming Ruth Anderson UW CSE 140 Winter
Decision Making CMSC 201. Overview Today we will learn about: Boolean expressions Decision making.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
An Object-Oriented Approach to Programming Logic and Design Chapter 5 Making Decisions.
Decision Making CMSC 201 Chang (rev ).
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Chapter 5 – Decision Making. Structured Programming Sequence Selection Repetition yesno yes no.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Today… Operators, Cont. Operator Precedence Conditional Statement Syntax. Winter 2016CISC101 - Prof. McLeod1.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
 Type Called bool  Bool has only two possible values: True and False.
Control Structures I Chapter 3
The Ohio State University
OBJECT ORIENTED PROGRAMMING I LECTURE 8 GEORGE KOUTSOGIANNAKIS
Operator Precedence Operators Precedence Parentheses () unary
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Topics The if Statement The if-else Statement Comparing Strings
Topics The if Statement The if-else Statement Comparing Strings
Python - Conditional Execution
Relational Operators Operator Meaning < Less than > Greater than
Comparing Strings Strings can be compared using the == and != operators String comparisons are case sensitive Strings can be compared using >, =, and.
Adding Intelligence Check for the presence or absence of a condition in the environment Take the appropriate actions Involves making a choice (to do or.
Python Programming Language
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
CHAPTER 5: Control Flow Tools (if statement)
Chapter 3: Selection Structures: Making Decisions
CprE 185: Intro to Problem Solving (using C)
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Presentation transcript:

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

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) CompSci 1012

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 ( ) invented Boolean algebra. CompSci 1013

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 = True has_won_game = True has_passed = True has_won_game = True age = True a = True age = True a = True Bad boolean variable names CompSci 1014

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) print(has_passed) print(has_won_game) has_passed = True has_won_game = has_passed has_passed = True has_won_game = has_passed CompSci 1015

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 thanless than or equal to CompSci 1016

Boolean variables  Variables can be used to store the result of a comparison, i.e., to store a boolean expressions  For example: exam_mark = 76 age = 8 points_so_far = 56 passed_exam = exam_mark >= 50 has_won_game = points_so_far > 70 is_old_enough = age > 10 is_old_enough = passed_exam != has_won_game print(passed_exam, has_won_game, is_old_enough ) exam_mark = 76 age = 8 points_so_far = 56 passed_exam = exam_mark >= 50 has_won_game = points_so_far > 70 is_old_enough = age > 10 is_old_enough = passed_exam != has_won_game print(passed_exam, has_won_game, is_old_enough ) True False True DEMO Example01.py CompSci 1017

Exercise 1  What is the output after executing the following code? val1 = 50 val2 = 53 diff = abs(val1 - val2) print("1. ", val1 != val2) print("2. ", val1 >= val2 - 3) print("3. ", val2 % 2 == 0) print("4. ", diff < 3) val1 = 50 val2 = 53 diff = abs(val1 - val2) print("1. ", val1 != val2) print("2. ", val1 >= val2 - 3) print("3. ", val2 % 2 == 0) print("4. ", diff < 3) CompSci 1018

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: andnot or CompSci 1019

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 > 8 Is 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 1 or CompSci 10110

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 < value < < value < 20 Is value greater than 10 and less than 20 CompSci 10111

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 ** CompSci 10112

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 CompSci 10113

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() 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() CompSci 10114

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 CompSci 10115

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. CompSci 10116

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. CompSci 10117

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: statement1 statement2 If the condition is true Conditional code If the condition is false Condition Indentation is important in Python (indicates the structure of code). Use one tab Be consistent with indentation Indentation is important in Python (indicates the structure of code). Use one tab Be consistent with indentation CompSci 10118

Example  What is the output after executing the following code?  Case 1:  Case 2 radius = -2 if radius >= 0: area = radius * radius * math.pi print("The area of the circle of radius", radius, "is", area) radius = -2 if 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.pi print("The area of the circle of radius", radius, "is", area) if radius >= 0: area = radius * radius * math.pi print("The area of the circle of radius", radius, "is", area) No output! NameError: name 'area' is not defined CompSci 10119

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") 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") BCBC CompSci 10120

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") number = int(input("Enter an integer: ")) if number % 5 == 0: print("HiFive!") if number % 2 == 0: print("HiEven") CompSci 10121

Exercise 4  What is the output after executing the following code? a = 42 b = 17 c = 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") a = 42 b = 17 c = 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") CompSci 10122

If statements – a common mistake  Remember that the equality operator is ==. What is the problem with the code below? val1 = 50 val2 = 53 if val1 = val2-3: print("Unbelievable") val1 = 50 val2 = 53 if val1 = val2-3: print("Unbelievable") Note: single = is the assignment operator. if val1 = val2-3: ^ SyntaxError: invalid syntax val1 = 50 val2 = 53 if val1 == val2-3: print("Unbelievable") val1 = 50 val2 = 53 if val1 == val2-3: print("Unbelievable") Unbelievable CompSci 10123

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.3 val2 = 0.1 * 3 if val1 == val2: print("Sigh!") if val1 != val2: print("maybe yes, maybe no!") val1 = 0.3 val2 = 0.1 * 3 if val1 == val2: print("Sigh!") if val1 != val2: print("maybe yes, maybe no!") maybe yes, maybe no! val1 = 0.3 val2 = 0.1 * 3 error_limit = if abs(val1 - val2) < error_limit: print("Close enough!") val1 = 0.3 val2 = 0.1 * 3 error_limit = if abs(val1 - val2) < error_limit: print("Close enough!") Close enough! CompSci 10124

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() def print_message(): def main(): print("Life will improve") print_message() main() Life will improve now Life will improve soon CompSci 10125

Algorithm  Complete the function: Generate a random number between 0 to 2If the number is 0, print “now”If the number is 1, print “soon”If the number is 2, print “never” CompSci 10126

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 CompSci 10127