Making Choices with if Statements

Slides:



Advertisements
Similar presentations
Chapter 4 - Control Statements
Advertisements

Computer Science 101 Overview of Algorithms. Example: Make Pancakes Prepare batter Beat 2 eggs Add 1 tablespoon of brown sugar Add 1 cup of milk Add 2.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Python Lab: Control Statements Conditionals, Loops, Iterations Proteomics Informatics, Spring 2014 Week 4 18 th Feb, 2014
Decision Structures and Boolean Logic
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.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
Flow of Control Part 1: Selection
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 4 Decision.
Computer Science 111 Fundamentals of Programming I Making Choices with if Statements.
Basic Control Structures
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Control statements Mostafa Abdallah
Chapter 3 Decisions Three control structures Algorithms Pseudocode Flowcharts If…then …else Nested if statements Code blocks { } multi statement blocks.
Midterm Exam Topics (Prof. Chang's section) CMSC 201.
8. DECISION STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
The If Statement There are no switch statements in Python. You need to use just if statements. There are no switch statements in Python. You need to use.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
Perl Chapter 3 Conditional statements. Control Expressions Control expressions – interpreted as T/F (evaluated as strings or numbers) – simple, relational,
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
IST 210: PHP Logic IST 210: Organization of Data IST2101.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
Chapter 3 Selections Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved
7 - Programming 7J, K, L, M, N, O – Handling Data.
Python Basics.
Control Flow (Python) Dr. José M. Reyes Álamo.
Chapter 4 Selections © Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Chapter 4: Control Structures I (Selection)
Chapter 3 Control Statements
Sequence, Selection, Iteration The IF Statement
Section 7.1 Logical Operators
Selections Java.
Python: Control Structures
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Chapter 5 Decisions. Chapter 5 Decisions ssential uestion: How are Boolean expressions or operators used in everyday life?
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Topics The if Statement The if-else Statement Comparing Strings
Selection UCT Department of Computer Science Computer Science 1015F
Control Structures – Selection
Topics The if Statement The if-else Statement Comparing Strings
Selection CIS 40 – Introduction to Programming in Python
And now for something completely different . . .
Chapter 7 Conditional Statements
Chapter 4 Selection.
3. Decision Structures Rocky K. C. Chang 19 September 2018
Summary Two basic concepts: variables and assignments Basic types:
Chapter 5: Control Structure
Computer Science Core Concepts
Chapter 4: Control Structures I (Selection)
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.
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Lecture Notes – Week 2 Lecture-2
Winter 2019 CISC101 4/16/2019 CISC101 Reminders
Chapter 3: Selection Structures: Making Decisions
Another Example Problem
The Selection Structure
Chap 7. Advanced Control Statements in Java
REPETITION Why Repetition?
Fundamentals of Python: First Programs Second Edition
Introduction to Python
Presentation transcript:

Making Choices with if Statements Computer Science 101 Making Choices with if Statements

Patterns of Control Sequencing - run one statement after another Iteration (loops) - run a given sequence of statements several times Pretty blind: always move straight ahead (perhaps many times)

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 not to do, that is the question!)

Asking Questions Is the number greater than 0? Are we at the end of the list? Does the file exist? Is the number divisible by 2?

Answers: Boolean Expressions Literals: True, False Variables Results of comparisons Results of logical operations

Comparisons Operators are ==, !=, <, >, <=, >= >>> x = 2 >>> x == 2 True >>> x < 3 >>> x > 4 False Operators are ==, !=, <, >, <=, >= == means equals, = means assignment != means not equal to

Example: Checking User Inputs A program will work only for inputs > 0 All other numbers should be rejected with an error message Only the positive inputs can be processed

The Area of a Circle import math radius = input('Enter the radius: ') area = math.pi * radius ** 2 print area This version allows negative inputs to be used - very bad!

Use an if-else Statement import math radius = input('Enter the radius: ') if radius <= 0: print 'ERROR: Input number must be positive!' else: area = math.pi * radius ** 2 print area This version checks the input and traps errors before they can cause damage The program responds gracefully with an error message

Syntax of if-else Statement import math radius = input('Enter the radius: ') if radius <= 0: print 'ERROR: Input number must be positive!' else: area = math.pi * radius ** 2 print area if <Boolean expression>: # The condition <sequence of statements> # The consequent else: <sequence of statements> # The alternative Also called a two-way if statement

Behavior of Two-Way if Statement Boolean expression False Alternative True Consequent if <Boolean expression>: # The condition <sequence of statements> # The consequent else: <sequence of statements> # The alternative

More Input Checking rate = input('Enter the interest rate[0-100]: ') interest = principal * rate / 100.0 print 'Your interest is', interest This version allows rates < 0 and rates > 100 Very bad!

More Input Checking rate = input('Enter the interest rate[0-100]: ') if rate < 0 or rate > 100: print 'ERROR: Rate must be between 0 and 100!' else: interest = principal * rate / 100.0 print 'Your interest is', interest Use comparisons and the logical operator or to restrict the rate to the legitimate values

The Logical Operators The Boolean expressions can be <Boolean expression> or <Boolean Expression> <Boolean expression> and <Boolean expression> not <Boolean expression> The Boolean expressions can be literals (True or False) variables comparisons Boolean function calls other expressions connected by logical operators

Truth Table for or rate = -1 print rate < 0 or rate > 100 True A B A or B True False Python stops evaluating operands when enough info is available to determine the result (short-circuit evaluation)

Truth Table for or In this case, both operands must be evaluated A B rate = 160 print rate < 0 or rate > 100 False True A B A or B True False In this case, both operands must be evaluated

Truth Table for or In this case, likewise A B A or B True False rate = 50 print rate < 0 or rate > 100 False False A B A or B True False In this case, likewise

Truth Table for and rate = -1 print rate >= 0 and rate <= 100 False A B A and B True False The and operator uses short-circuit evaluation, too

Truth Table for and A B A and B True False rate = 50 print rate >= 0 and rate <= 100 True True A B A and B True False

Truth Table for and A B A and B True False rate = 160 print rate >= 0 and rate <= 100 A B A and B True False

Truth Table for not import os.path filename = input('Enter the file name: ') if not os.path.isfile(filename): print 'ERROR: File does not exist!' else: # Process the file A not A True False

Precedence of Logical Operators print False or True and not True # Same as print False or (True and (not True)) Ranking: not (logical negation) and (logical product) or (logical sum)

Multiple Conditions rate = input('Enter the interest rate[0-100]: ') if rate < 0 or rate > 100: print 'ERROR: Rate must be between 0 and 100!' else: interest = principal * rate / 100.0 print 'Your interest is', interest An alternative way to write this is to use a series of if statements with different conditions

Multiway if Statement rate = input('Enter the interest rate[0-100]: ') if rate < 0: print 'ERROR: Rate must be greater than 0!' elif rate > 100: print 'ERROR: Rate must be less than 101!' else: interest = principal * rate / 100.0 print 'Your interest is', interest if <Boolean expression>: # The first condition <sequence of statements> # The first consequent elif <Boolean expression>: # The second condition <sequence of statements> # The second consequent … else: <sequence of statements> # The default alternative

A One-way if Statement Also called a one-way if statement if number < 0: number = -number Also called a one-way if statement If the comparison returns True, run the nested statement Otherwise, do nothing if <Boolean expression>: # The condition <sequence of statements> # The consequent

Behavior of One-Way if Statement Boolean expression False True Consequent if <Boolean expression>: # The condition <sequence of statements> # The consequent

Review Loops in Chapters 1 and 2 For Wednesday Review Loops in Chapters 1 and 2