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

Similar documents
CS 115 Lecture 4. More Python; testing software. Neil Moore

cs1114 REVIEW of details test closed laptop period

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

Chapter 4: Making Decisions

Chapter 4: Making Decisions

LECTURE 04 MAKING DECISIONS

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Text Input and Conditionals

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

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

CS 115 Lecture 13. Strings. Neil Moore. Department of Computer Science University of Kentucky Lexington, Kentucky

Decisions, Decisions. Testing, testing C H A P T E R 7

CS 115 Lecture 21. Classes, data structures, and C++ Neil Moore

Control Structures in Java if-else and switch

CS 115 Lecture. Boolean logic Taken from notes by Dr. Neil Moore

ENGR 101 Engineering Design Workshop

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Control Structures in Java if-else and switch

Lecture 2: Variables & Assignments

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

Full file at

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Fundamentals of Programming (Python) Getting Started with Programming

Lecture 1. Types, Expressions, & Variables

Java Fall 2018 Margaret Reid-Miller

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Flow Control: Branches and loops

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

How Do Robots Find Their Way?

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

Conditionals and Recursion. Python Part 4

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

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

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

Getting Started with Python

Spring 2017 CS 1110/1111 Exam 1

CMSC 201 Computer Science I for Majors

CS 111X - Fall Test 1

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Python for Informatics

CS 111X - Fall Test 1 - KEY KEY KEY KEY KEY KEY KEY

Introduction to Python

PYTHON- AN INNOVATION

Program Planning, Data Comparisons, Strings

CS 1301 Exam 1 Fall 2010

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

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Python: common syntax

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

Conditionals and Loops

Lists, loops and decisions

Last Name: First Name: Cornell NetID, all caps: CS 1110 Regular Prelim 1 Solutions March 2018

CS 1110, LAB 1: PYTHON EXPRESSIONS.

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

Visual C# Instructor s Manual Table of Contents

CS1004: Intro to CS in Java, Spring 2005

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Loop structures and booleans

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

(the bubble footer is automatically inserted into this space)

The following expression causes a divide by zero error:

CSCI 1101B. Boolean Expressions

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

CS313D: ADVANCED PROGRAMMING LANGUAGE

Conditional Expressions and Decision Statements

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

5. Selection: If and Switch Controls

Lecture 1. Course Overview, Python Basics

Getting Started Values, Expressions, and Statements CS GMU

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

CS1 Lecture 3 Jan. 18, 2019

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Oct Decision Structures cont d

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

Microsoft Visual Basic 2005: Reloaded

CS 1301 Exam 1 Answers Fall 2009

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

CS1 Lecture 3 Jan. 22, 2018

CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Comp 151. Control structures.

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

egrapher Language Reference Manual

The current topic: Python. Announcements. Python. Python

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Lecture 1. Course Overview, Python Basics

Lecture 5 Tao Wang 1

3. Conditional Execution

CS 1301 Exam 1 Fall 2014

Transcription:

CS 115 Lecture 8 Selection: the if statement Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 24 September 2015

Selection Sometime we want to execute code only sometimes. Run this code in a certain situation. How to express in a certain situation in code? Run this code if this expression is true. So we d need true-false expressions. We mentioned a true-false type in the second week of class. bool (Booleans) Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 2 / 19

The boolean type The type bool in Python represents a value that is either true or false. Two literals (constant values): True and False Case-sensitive as always! Can have boolean variables: is finished = False Sometimes called flags (more on this when we get to loops)... and boolean expressions: is smallest = number < minimum can run = have file and is valid Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 3 / 19

Naming boolean variables This isn t a hard-and-fast rule, but try to name boolean variables as a sentence or sentence fragment: Is this item selected? is selected Is the user a new user? user is new (or is user new) Does the program have an input file? have input file Does the user want the answer in meters? want meters Why is selected and not just selected? Ambiguous: it could also mean which item was selected? Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 4 / 19

Type-casting to bool Most types can be type-cast to bool. Usually the meaning is something like is there anything there? Numbers: 0 (or 0.0) is false, nonzero is true. Be careful with floats: 0.3-3 * 0.1 is not exactly zero! Strings: the empty string "" is false, anything else is true. All graphics shapes are true. Even Point(0, 0)! Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 5 / 19

Equality and inequality Other than literal True and False, the simplest boolean expressions compare the values of two expressions. Less than, greater than,... Even simpler: is equal to and is not equal to. The equal sign is already taken (for assignment). So equality testing uses == logged in = password == "hunter1" No spaces between the =! It s kind of hard to type, so Python uses!= for is not equal to : need plural = quantity!= 1 did fail = actual!= expected == compares values, is asks are they aliases. Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 6 / 19

Comparison Besides equality and inequality, Python has four more comparison, or relational, operators: Less than and greater than: score < 60 damage > hit points Less than or equal to (less-equals), greater-equals: students <= seats score > 60 The opposite of < is >=: a < b is false if a >= b is true. Precedence: lower than arithmetic, higher than assignment. need alert = points + bonus < possible * 0.60 is the same as: need alert = ((points + bonus) < (possible * 0.60)) Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 7 / 19

Relational operators and types What type do the relational operators return (i.e. the result)? bool What types can be compared with relational operators? Numbers: ints and floats. str what does it mean to compare two strings? ASCIIbetical order Like alphabetical order, but considers all characters. Characters are compared by their Unicode value. blu-ray < blue because - comes before e Uppercase Z comes before lowercase a! Relational operators cannot mix strings and numbers! 3 < "Hello" TypeError: unorderable types: int() < str() It s okay to mix ints and floats, though. Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 8 / 19

The if statement Now that we can write some boolean expressions, how do we use those to control whether or not certain code executes? Use an if statement. Syntax: if expression : body The expression should evaluate to True or False. The body is an indented block of code. Semantics: Evaluates the expression. Runs the body if it was true. Goes on to the line after the body either way. Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 9 / 19

Flowchart for if before the if before the if if expression: body after the if expression? True body False after the if Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 10 / 19

Alternatives: else Commonly we want to either do this or do that (but not both). In Python we can use an else block. Syntax: if expression : if-body else: else-body Both bodies are indented blocks. No expression after else! Can t have an else without an if! Semantics: Evaluates the expression. If the expression is true, runs the if-body. Otherwise (it was false), runs the else-body. Either way, goes on to the line after the else-body. Only use else if there is something to do in the false case. It s okay not to have one! Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 11 / 19

Flowchart for if-else before the if before the if if expression: if-body else: else-body after the if else-body False expression? True if-body after the if Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 12 / 19

Many alternatives Sometimes there are more than two alternatives. Converting a numeric score into a letter grade: If the score is greater than or equal to 90, print A. Otherwise, if score >= 80, print B. Otherwise, if score >= 70, print C. And so on... We want to run exactly one piece of code. Even though 95 >= 70, we don t want 95 to print C too! First, check if score >= 90. If that was false, check if score >= 80. If that was false too, check if score >= 70... The order matters! What would happen if we swapped the order of B and C? Then we d never report a B! Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 13 / 19

Chained alternatives: elif Syntax: if expression 1 : body 1 elif expr 2 : body 2 elif expr 3 : body 3... Semantics: Each elif is followed by an expression. And a colon. Each body is an indented block. Can have an else block at the very end. Not required! Evaluates expression 1. If expression 1 was true, runs body 1 (and that s all) If expression 1 was false, evaluates expression 2. If expression 2 was true, runs body 2 (and that s all) If expression 2 was false, evaluates expression 3... After running at most one body, goes on to the next line. Only runs one body, or none (the first true expression) Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 14 / 19

Flowchart for if-elif True expr 1? body 1 False True expr 2? body 2 if expr1: body1 elif expr2: body2 elif expr3: body3 after False True expr 3? body 3 False after Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 15 / 19

Open and closed selection If there is an else, the selection is closed Meaning exactly one of the bodies will run. Otherwise, it is open: zero or one bodies will run. If the last elif is supposed to cover all the remaining cases, prefer else instead: if score >= 90: grade = A : elif score >= 80: grade = B : elif score >= 70: grade = C : elif score >= 60: grade = D : elif score < 60: else: grade = E : Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 16 / 19

When and how to use elif divisible.py divisible-better.py divisible-best.py If you want more than one body to execute, you don t want elif. Instead, use a sequence of separate ifs. Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 17 / 19

Testing ifs When testing programs with if statements, be sure to consider and test all the possible outcomes. If your tests never execute a particular line, you don t know if it works! For every if or if-else you should have two cases: One where it is true. One where it is false even if there is no else. For a chained if-elif, test: Expression 1 is true. Expression 1 is false, 2 is true. Expressions 1 and 2 are false, 3 is true.... All the expressions are false. If plus N elifs: N + 2 test cases! Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 18 / 19

More testing It helps to consider combinations of separate if statements, too. Especially when they use the same variable(s): if user!= "hunter": is valid = False if password!= "hedges": is valid = False We might have four test cases for these two ifs: User name right, password right. User name right, password wrong. User name wrong, password right. User name wrong, password wrong. Finally, when testing comparisons, check the boundary cases: What if the score is exactly 60.0? What if the score is 59.9? Neil Moore (UK CS) CS 115 Lecture 8 Fall 2015 19 / 19