Topics: IF If statements Else clauses. IF Statement For the conditional expression, evaluating to True or False, the simple IF statement is if : x = 7.

Slides:



Advertisements
Similar presentations
CSC 110 Decision structures [Reading: chapter 7] CSC 110 H1.
Advertisements

1 Decision Structures Chapter 7 (Skip 7.1.3, 7.4) Adapted from the online slides provided by John Zelle (
James Tam Making Decisions In Python In this section of notes you will learn how to have your Pascal programs choose between alternative courses of action.
1 9/26/08CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
Python Programming: An Introduction to Computer Science
Making Decisions In Python
The If/Else Statement, Boolean Flags, and Menus Page 180
C++ for Engineers and Scientists Third Edition
Decision Making George Mason University. Today’s topics 2 Review of Chapter 2: Decision Making Go over exercises Decision making in Python.
Decisions in Python elif. A new keyword elif A contraction of “else if” Used to tie two if statements (or more) together into one structure Syntax – elif,
1 9/28/07CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 03.
Chapter 3 Computing with Numbers
Chapter 7 Decision Structures
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers.
Python Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 2/e1.
Exceptions COMPSCI 105 S Principles of Computer Science.
Decision Structures and Boolean Logic
Chapter 3 Making Decisions
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
Conditional Control Flow Constructs. Sequential Control Flow Execution order follows the textual order straight line flow Many simple problems can not.
If statements while loop for loop
Fall, 2006Selection1 Choices, Choices, Choices! Selection in FORTRAN Nathan Friedman Fall, 2006.
1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
Decisions in Python Bools and simple if statements.
1 Example: Solution of Quadratic Equations We want to solve for real values of x, for given values of a, b, and c. The value of x can be determined from.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Topics: Function Intitution Algorithm Example Function Definition (and Indentation) Function Call Naming and Binding Local Variables Function Arguments.
Decision Making CMSC 201. Overview Today we will learn about: Boolean expressions Decision making.
Python Conditionals chapter 5
CS 106 Introduction to Computer Science I 09 / 26 / 2007 Instructor: Michael Eckmann.
Xiaojuan Cai Computational Thinking 1 Lecture 7 Decision Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
Variables, Types, Expressions Intro2CS – week 1b 1.
8. DECISION STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(
CS 127 Exceptions and Decision Structures. Exception Handling This concept was created to allow a programmer to write code that catches and deals with.
Decision Making CMSC 201 Chang (rev ).
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Control Statements: Part1  if, if…else, switch 1.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 CS Review, iClicker -Questions Week 15. Announcements 2.
Announcements Reading Read Chapter 4 (functions).
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Python Programming, 3/e1 Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures.
Python Boot Camp Booleans While loops If statements Else clauses
Python Programming: An Introduction to Computer Science
Introduction to Python
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Python Programming: An Introduction to Computer Science
Midterm Exam 答題分布 Python Programming, 2/e.
Class 12.
Conditional and iterative statements
15-110: Principles of Computing
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Class 13 function example unstring if if else if elif else
Winter 2019 CISC101 4/16/2019 CISC101 Reminders
Chapter 3: Selection Structures: Making Decisions
COMPUTER PROGRAMMING SKILLS
月夜憶舍弟 戍鼓斷人行,邊秋一雁聲。 露從今夜白,月是故鄉明。 有弟皆分散,無家問死生。 寄書長不達,況乃未休兵。 杜甫
月夜憶舍弟 戍鼓斷人行,邊秋一雁聲。 露從今夜白,月是故鄉明。 有弟皆分散,無家問死生。 寄書長不達,況乃未休兵。 杜甫
Jurassic Park Python Programming, 2/e.
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
Presentation transcript:

Topics: IF If statements Else clauses

IF Statement For the conditional expression, evaluating to True or False, the simple IF statement is if : x = 7 if x > 10: print (x) x = x + 1 x = True if x: print (x)

Conditionals It is also possible to specify what to do if the condition is False. Contrast these two examples. x = 7 if x > 10: print (x) x = x + 1 x = 7 if x > 10: print (x) else: x = x + 1

if x > 10 print (x) x = x + 1 True False x = 7 if x > 10: print (x) x = x + 1

if x > 10 print (x) TrueFalse x = 7 if x > 10: print (x) else: x = x + 1

Conditions At the heart of a conditional is a condition evaluation The code after the if but before the : should evaluate to either True or False These are special keywords in Python and are case sensitive

Beyond True and False Python provides True and False, even for general values Numbers:zero ≡ False, not zero ≡ True Lists: [ ] ≡ False, any other list ≡ True Strings:“” ≡ False, any other string ≡ True Experiment with it! x = 0 if 1: print (x) x = 0 if 0: print (x)

Do these programs print the same things? # 1 x = 7 if x > 10: print (x) x = x + 1 print (x) #2 x = 7 if x > 10: print (x) else: x = x + 1 print (x) (a)Yes (b)No

CQ: Do these programs print the same things? 2 1 A: yes B: no x = 12 if x > 10: print (x) x = x + 1 print (x) x = 12 if x > 10: print(x) else: x = x + 1 print(x)

Therefore Always ask what “equivalent” means… For us from now on: Two programs are equivalent if they give the same output for all inputs Any other meaning should be made clear by explicit wording

Some Interesting Observations Comparisons can be chained x < y <= z is equivalent to: x < y and y <= z The not operator has a lower order of precedence than comparisons not a == b is equivalent to: not( a== b)

Clicker Question Now we can start building useful conditions Does this check if x > 0? if x and y > 0: print( x, y ) A: yes B: no

Tests Continued We could write such a condition as follows: if x > 0 and y > 0: print (x + y)

Clicker Question: Are these programs equivalent? if (x+y) < 10: print(x) if (x+y)>=10: print(y) if(x+y) < 10: print(x) else: print(y) 21 A: yes B: no

Are these programs equivalent? #1 if (x+y) < 10: print(x) if (x+y)>=10: print(y) #2 if(x+y) < 10: print(x) else: print(y) (a)Yes (b)No

Nested Conditionals if x < 10: print(x+y) if y < 100: print(x) else: print(y)

Why nested conditionals? We could just write many complex conditionals and avoid the nested conditionals This is inefficient (many redundant checks) and may lead to code duplication But is the nesting always easy to understand?

Example Revisited if x < 10 and y < 100: print(x+y) print(x) if x = 100: print(x+y) print(y) if x < 10: print(x+y) if y < 100: print(x) else: print(y)

Defensive Coding Comment your code Use conditionals to check/verify assumptions Use variable names that have meaning Avoid reusing variable names Use parentheses when order matters Keep the code simple

Keeping it simple def minOfThree(a,b,c): if a<=b and a<=c: return a if b<=a and b<=c: return b if c<=a and c<=b: return c

Keeping it simple? def minOfThree(a,b,c): if a<=b: if a<=c: return a else: return c else: if b<=c: return b else: return c

Analysis def minOfThree(a,b,c): if a<=b: if a<=c: return a else: return c else: if b<=c: return b else: return c a<=b a<=c b<=c y y y n n n a b c c

Analysis a<=b a<=c b<=c y y y n n n not b! not a! a b c c Who can be min? def minOfThree(a,b,c): if a<=b: if a<=c: return a else: return c else: if b<=c: return b else: return c

Clicker Question 1 if “False”: print(“hi”) 2 if False: print(“hi”) A: 1 and 2 both print B: only 1 prints C: only 2 prints D: neither 1 nor 2 print

Clicker Question 3 if eval(“False”): print(“hi”) 2 if False: print(“hi”) A: 3 and 2 both print B: only 3 prints C: only 2 prints D: neither 3 nor 2 print

#1 if eval(“False”): print(“hi”) #2 if False: print(“hi”) (a): 3 and 2 both print (b): only 3 prints (c): only 2 prints (d): neither 3 nor 2 print

CQ explained 1: nonempty string means True 2: condition is False 3: eval(“False”) is False Therefore only 1 will print if False: print(“hi”) if eval(“False”): print(“hi”) if “False”: print(“hi”)

Error Checking Revisited #This function expects two positive integers # Returns -1 as an error condition def sumOfTwo(a,b): if type(a) == int and type(b) == int : if a > 0 and b > 0: return a+b return -1

Error Checking Revisited #This function expects two positive integers # Returns -1 as an error condition def sumOfTwo(a,b): if type(a) == int and type(b) == int : if a > 0 and b > 0: return a+b else: return -1

Two-Way Decisions import math def main(): print("This program finds the real solutions to a quadratic”) a,b,c=eval(input("\nPlease enter coefficients (a, b, c): ")) discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print("\nThe solutions are:", root1, root2) main()

Two-Way Decisions As per the comment, when b 2 -4ac < 0, the program crashes. This program finds the real solutions to a quadratic Please enter coefficients (a, b, c): 1,1,2 Traceback (most recent call last): File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 120\Textbook\code\chapter3\quadratic.py", line 21, in -toplevel- main() File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 120\Textbook\code\chapter3\quadratic.py", line 14, in main discRoot = math.sqrt(b * b - 4 * a * c) ValueError: math domain error

Two-Way Decisions We can check for this situation. Here’s our first attempt. # quadratic2.py # A program that computes the real roots of a quadratic equation. # Bad version using a simple if to avoid program crash import math def main(): a, b, c = eval(input("Please enter the coefficients (a, b, c): ")) discrim = b * b - 4 * a * c if discrim >= 0: discRoot = math.sqrt(discrim) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print("\nThe solutions are:", root1, root2)

Two-Way Decisions We first calculate the discriminant (b 2 -4ac) and then check to make sure it is not negative. If it is, the program proceeds and we calculate the roots. Look carefully at the program. What’s wrong with it? Hint: What happens when there are no real roots?

Two-Way Decisions This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1,1,1 >>> This is almost worse than the version that crashes, because we don’t know what went wrong!

Two-Way Decisions We could add another if to the end: if discrim < 0: print("The equation has no real roots!" ) This works, but feels wrong. We have two decisions, with mutually exclusive outcomes (if discrim >= 0 then discrim < 0 must be false, and vice versa).

Two-Way Decisions

# quadratic3.py # A program that computes the real roots of a quadratic equation. # Illustrates use of a two-way decision import math def main(): print "This program finds the real solutions to a quadratic\n" a,b,c = eval(input("Please enter the coefficients (a, b, c): ")) discrim = b * b - 4 * a * c if discrim < 0: print("\nThe equation has no real roots!") else: discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print ("\nThe solutions are:", root1, root2 ) main()

Two-Way Decisions >>> This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1,1,2 The equation has no real roots! >>> This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 2, 5, 2 The solutions are:

Multi-Way Decisions The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1,2,1 The solutions are:

Multi-Way Decisions While correct, this method might be confusing for some people. It looks like it has mistakenly printed the same number twice! Double roots occur when the discriminant is exactly 0, and then the roots are –b/2a. It looks like we need a three-way decision!

Multi-Way Decisions Check the value of discrim when 0: handle the case of two distinct roots We can do this with two if-else statements, one inside the other. Putting one compound statement inside of another is called nesting.

Multi-Way Decisions if discrim < 0: print("Equation has no real roots") else: if discrim == 0: root = -b / (2 * a) print("There is a double root at", root) else: # Do stuff for two roots

Multi-Way Decisions

Imagine if we needed to make a five-way decision using nesting. The if-else statements would be nested four levels deep! There is a construct in Python that achieves this, combining an else followed immediately by an if into a single elif.

Multi-Way Decisions if : elif : elif :... else:

Multi-Way Decisions This form sets of any number of mutually exclusive code blocks. Python evaluates each condition in turn looking for the first one that is true. If a true condition is found, the statements indented under that condition are executed, and control passes to the next statement after the entire if-elif-else. If none are true, the statements under else are performed. The else is optional. If there is no else, it is possible no indented block would be executed.

Multi-Way Decisions Conditions need not be mutually exclusive. Therefore, changing the sequence may give different results! Consider the following two versions when a==0 and b==2 if b<0: x=1 elif b>0 and a<3: x=2 elif b>0: x=3 else: x=4 if b<0: x=1 elif b>0: x=3 elif b>0 and a<3: x=2 else: x=4

Multi-Way Decisions def main(): a, b, c = eval(input("Please enter the coefficients (a, b, c): ")) discrim = b * b - 4 * a * c if discrim < 0: print("\nThe equation has no real roots!") elif discrim == 0: root = -b / (2 * a) print("\nThere is a double root at", root) else: discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print("\nThe solutions are:", root1, root2 )

Which version is simpler? def sort3(a,b,c): if a<=b: if b<=c: return [a,b,c] elif a<=c: return [a,c,b] else: return [c,a,b] else: if a<=c: return [b,a,c] elif b<=c: return [b,c,a] else: return [c,b,a] def sort3(a,b,c): if a<=b: if b<=c: return [a,b,c] else: if a<=c: return [a,c,b] return [c,a,b] else: if a<=c: return [b,a,c] else if b<=c: return [b,c,a] return [c,b,a]