Control Flow: Branching booleans and selection statements CS GMU

Similar documents
Conditionals and Recursion. Python Part 4

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

Lecture 8: Conditionals & Control Flow (Sections ) CS 1110 Introduction to Computing Using Python

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

CSE 115. Introduction to Computer Science I

logical operators and else-if statements

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Lecture 02 Making Decisions: Conditional Execution

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block

boolean Expressions Relational and Equality Operators and if-then-else Conditional Control Statement

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Flow Control. So Far: Writing simple statements that get executed one after another.

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Practice with if-then-else. COMP101 Lecture 7 Spring 2018

Control Structures 1 / 17

Flow Control: Branches and loops

Chapter 8. Statement-Level Control Structures

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

Python for Informatics

Text Input and Conditionals

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

Python Programming: An Introduction to Computer Science

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

Computer Science 217

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Scripting Languages. Python basics

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Motivation for typed languages

C ONTROL AND H IGHER O RDER F UNCTIONS

CSE 115. Introduction to Computer Science I

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

ME30 Lab3 Decisions. February 20, 2019

Circuit analysis summary

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Conditionals & Control Flow

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Chapter 8. Statement-Level Control Structures

(Python) Chapter 3: Repetition

Crude Video Game Simulator Algorithm

CS 61A Control and Environments Spring 2018 Discussion 1: January 24, Control. If statements. Boolean Operators

boolean & if-then-else

CONTROL AND ENVIRONMENTS 1

Quiz. Introduction: Python. In this project, you ll make a quiz game to challenge your friends. Activity Checklist.

Test #2 October 8, 2015

Lecture 3 (02/06, 02/08): Condition Statements Decision, Operations & Information Technologies Robert H. Smith School of Business Spring, 2017

Decision Structures CSC1310. Python Programming, 2/e 1

Comp 151. Control structures.

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Chapter 8. Statement-Level Control Structures ISBN

Chapter 8. Statement-Level Control Structures

Conditionals: Making Choices

CS100 Spring 2012 Midterm 1 Practice

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Introduction to Programming

Making Decisions In Python

cs1114 REVIEW of details test closed laptop period

Most of the class will focus on if/else statements and the logical statements ("conditionals") that are used to build them. Then I'll go over a few

Conditional Expressions

Chapter 4 The If Then Statement

The following expression causes a divide by zero error:

CS100: CPADS. Decisions. David Babcock / Don Hake Department of Physical Sciences York College of Pennsylvania

Hello, World! An Easy Intro to Python & Programming. Jack Rosenthal

Boolean algebra. June 17, Howard Huang 1

Chapter 8 Statement-Level Control Structures

Conditional Expressions and Decision Statements

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

Comp 151. Control structures.

CS1 Lecture 5 Jan. 25, 2019

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

MATLAB Operators, control flow and scripting. Edited by Péter Vass

CONTROL AND HIGHER ORDER FUNCTIONS 1

Programming in Python 3

61A Lecture 3. Friday, September 5

Lecture 04 More Iteration, Nested Loops. Meet UTA Jarrett s dog Greta, lying in her nest

Computers and FORTRAN Language Fortran 95/2003. Dr. Isaac Gang Tuesday March 1, 2011 Lecture 3 notes. Topics:

CS1 Lecture 5 Jan. 26, 2018

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

5. Control Statements

Case by Case. Chapter 3

Python Games. Session 1 By Declan Fox

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Getting Started Values, Expressions, and Statements CS GMU

Logical and Bitwise Expressions

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016

Strings and Testing string methods, formatting testing approaches CS GMU

Selection statements. CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington

CS 2316 Exam 1 Spring 2014

How Do Robots Find Their Way?

CS Boolean Statements and Decision Structures. Week 6

Intro. Scheme Basics. scm> 5 5. scm>

Conditionals. C-START Python PD Workshop

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

CS177 Recitation. Functions, Booleans, Decision Structures, and Loop Structures

Intro. Comparisons. > x > y if and only if x is bigger than y. < x < y if and only if x is smaller than y.

Transcription:

Control Flow: Branching booleans and selection statements CS 112 @ GMU

Topics booleans selection statements: if if-else if-elif(s) if-elif(s)-else flow charts 2

Booleans

Booleans - examples Booleans are either True or False. We create them in many ways. 3<4 True 17%2==0 False 2<5 or 10>20 True not True False "hello"=="hello" False

Booleans definition bool is another Python type. It has exactly two values: True, False. many operators and functions will result in a boolean value they can be used to make decisions: if an expression results in True, do one thing (run one block of code); if False, do another thing (go to a different place in code)

Booleans operators three main operations that we do with booleans: and, or, not expr1 and expr2: are both exprs True? expr1 or expr2: is at least one expr True? not expr: switch between True/False

Booleans truth tables We can exhaustively describe all combinations of inputs for and, or, and not. x y x and y x y x or y x not x False False False False False False False True False True False False True True True False True False False True False True True True True True True True

Booleans more operators numbers and other types of values can be used to generate booleans with various operators: operator meaning arguments a < b less than numbers a <= b less than or equal numbers a > b greater than numbers a >= b greater than or equal numbers a == b equality check anything! a!= b inequality check anything!

Poll 2.1 (boolean expressions) 1.Given this code, answer each with the result of the expression. x=2 y=4 a) (x<y) and b b=true b) (not b)==false c) 3>y and x<=y d) "test" == "Test" 2. Only knowing that x, y, and z are integers, what is the result of the following expression? (not (x<y and y<z)) == (x>=y or y>=z))

Chained Comparisons Python is a bit unique in allowing chained comparisons: x<y<=z is equivalent to (x<y) and (y<=z) short circuiting: from left to right, if any relation in the chain is False, we know the overall answer is False, so no further relations are checked. (above: if x<y is False, don't check y<=z)

Impostors! Python will happily and silently (and unfortunately) let us use non-booleans where boolean values are expected zero numbers are treated as False non-zero numbers are all treated as True other non-booleans have boolean interpretations too Suggestion: try to only use actual boolean expressions where booleans are needed!

TRAP Note the difference: x = 5 x == 5 assignment statement boolean expression Python can tell if you put an assignment where an expression should go, but will not complain when an expression is where an assignment should go.

more boolean expressions Assume that x=2, y=4, b=true. Simplify each expression. x<y not (3<y) (x<y) and b not (not b) x<y<b "test"=="test" 3>y "test"=="test" 3>y and x<=y not b == y<x 3>y or x<=y x+x == y False == False False == (not b)

more boolean expressions Assume that x=2, y=4, b=true. Simplify each expression. True x<y False not (3<y) True (x<y) and b True not (not b) (False!) x<y<b True "test"=="test" False 3>y False "test"=="test" False 3>y and x<=y True not b == y<x True 3>y or x<=y True x+x == y True False == False True False == (not b)

Branching

selection statements we can select different blocks of code to run based on a boolean expression's value: dist = int(input("dist?")) if dist >= 26.2: print("marathon, wow!") print("good run.") if payment>cost: change = payment cost print("change: "+str(change)) else: print("not enough money!") val=int(input("temperature: ")) if val > 80: print("hot today.") elif val >= 65: print("i can manage.") else: print("where's my jacket?")

if-statement an if-statement guards a block of code with a boolean expression. if the expression is True, then run the block if the expression is False, then skip the block decision: do I perform or skip this indented block of statements? if expr: stmts

if-else statement an if-else statement guards two blocks of code with a boolean expression. if expr is True, then run only the first block if expr is False, then run only the second block decision: which of two blocks of code do I run? if expr: stmts1 else: stmts2

if-elif statement an if-elif statement guards two or more blocks of code with multiple boolean expressions. check each boolean expr in order until you find the first True one. Only run corresponding block of code may have a single else block at the end Decision: which of many things to run? no else block: might run none of them if expr1: stmts1 elif expr2: stmts2 elif expr3: stmts3 else: stmtsn

Selection statement example 1 val = int(input("number to check: ")) if val==10: print("ten is great!") print("thanks!") we only print "ten is great!" when val currently stores 10; other Ymes, we skip that indented code. "thanks!" always prints, because it follows the if-statement (it isn't indented)

Selection statement example 2 val = int(input("number to check: ")) if val==10: print("a: ten is great!") else: print("b: I dislike that number.") print("thanks!") we always print either message A or B, but not both. "thanks!" always prints, because it follows the selecyon statement

Selection statement example 3 val = int(input("number to check: ")) if val<10: print("a: small number") elif val==10: print("b: perfect size!") else: print("c: too big.") print("thanks!") we always print exactly one of messages A or B or C, but not mulyple of them, and not zero of them. we could omit the else branch, and for big inputs only "thanks!" would print. "thanks!" always prints, because it follows the selecyon stmt

Selection statement example 4 val = int(input("number to check: ")) if val<10: print("a: small number") elif val==10: print("b: perfect size!") elif val<100: print("c: a bit too big.") print("thanks!") we print at most one of messages A or B or C "thanks!" always prints, because it follows the selecyon stmt

note: else blocks the else block is an optional addition to a selection statement, whether it has zero, one, or many elif branches. it always defines the "default" behavior: when none of the boolean expressions were True, this else block is what should be run.

Poll 2.2 (selection statements) 1. What is the final value of x? x = 5 if x>0: x += 3 if x>6: x += 10 if x>100: x = 123 2. What is the final value of x? x = 15 if x%7>1: x = x + 100 else: x = x + 6 if x%3==0: x = x * 2 3. What is the final value of x? x = 20 if x > 25: x += 100 if x > 15: x += 200 if x > 5: x += 400

flow charts branches in flow charts have multiple paths that split and rejoin they can become selection statements: each separate path is an if/elif/else block one separate path may itself contain further subdivisions/splits that rejoin to each other (nested selection statements)

selections, flow charts - example guess = int(input("your guess: ")) secret = 42 True get number guess from user too high? False if guess > secret: print("too big.") elif guess < secret: print("too small.") else: print ("correct!") print "too big" True print "too small" too low? False print "correct!" print ("thanks for guessing!") thanks for guessing!

practice: flow chart to code #1 True c False if c : s1 s2 s1 s2

practice: flow chart to code #2 True c1 False if c1 : s1 True s2 c2 False s1 elif c2: s2 s3 s3

practice: flow chart to code #3 True c1 False if c1 : s1 True c2 False s1 elif c2: s2 s3 s2 else: s4 s4 s3

practice: flow chart to code #4 s1 s2 s3 True True True s0 c1 c2 c3 False False False s0 if c1: s1 if c2: s2 if c3: s3 s4 what possible paths are there through this code? would this code behave differently if we used elif's for c2 and c3? s4

practice: flow chart to code #5 s1 True c1 False s4 if c1: s1 if c2: True c2 False True c3 False s3 s2 s2 s5 s6 else: s4 s3 True s7 c4 False if c3: else: s5 s6 s8 if c4: s7 s9 s9 s8

Poll 2.3 1. What is the final value of x? x = 10 if x==20: x = 100 elif x>5: if x<50: x += 1 else: x += 4 elif x>=0: x = 3 if x%2==1: x += 1000 (selection statements) 2. Match each usage to a description. #1 if else #2 if elif #3 if elif elif else #4 if if if #5 if a) three separate choices to do or not do separate blocks of code b) select whether to do something or not c) select one or another action or alternatively do nothing d) select one of many blocks of code e) select one of two things to do

selection statements recap if: choose whether to run a block of code or not, based upon a boolean expression if-else: choose which of two things to do if-elif(s): choose one of many blocks of code, by finding first True boolean expr. Might choose none of them (all were False) if-elif(s)-else: choose exactly one of many blocks of code, by finding first True boolean expr (or running else block when all were False) flow charts: there are direct mappings between flow chart shapes and code.