4 If-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming.

Slides:



Advertisements
Similar presentations
Copyright © 2003 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 2 Flow of Control. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 2-2 Learning Objectives Boolean Expressions Building, Evaluating.
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
= (x + 6) (x + 2) 1. x2 +8x x2 +16x + 48 = (x + 12) (x + 4)
0 - 0.
ALGEBRAIC EXPRESSIONS
DIVIDING INTEGERS 1. IF THE SIGNS ARE THE SAME THE ANSWER IS POSITIVE 2. IF THE SIGNS ARE DIFFERENT THE ANSWER IS NEGATIVE.
ADDING INTEGERS 1. POS. + POS. = POS. 2. NEG. + NEG. = NEG. 3. POS. + NEG. OR NEG. + POS. SUBTRACT TAKE SIGN OF BIGGER ABSOLUTE VALUE.
SUBTRACTING INTEGERS 1. CHANGE THE SUBTRACTION SIGN TO ADDITION
MULT. INTEGERS 1. IF THE SIGNS ARE THE SAME THE ANSWER IS POSITIVE 2. IF THE SIGNS ARE DIFFERENT THE ANSWER IS NEGATIVE.
Addition Facts
1 Functional Programming Lecture 8 - Binary Search Trees.
Automata Theory Part 1: Introduction & NFA November 2002.
Chapter 4: Basic Estimation Techniques
CS 3630 Database Design and Implementation. Where Clause and Aggregate Functions -- List all rooms whose price is greater than the -- average room price.
LIAL HORNSBY SCHNEIDER
© S Haughton more than 3?
Quadratic Inequalities
Pemrograman Dasar Control Flow Statements: Decision Making or Selection PTIIK - UB 1.
3.2 Chapter 3 Quadratic Equations. To solve quadratic equations by factoring, apply the which states that, if the product of two real numbers is zero,
Absolute-Value Equations and Inequalities
Discrete Mathematics Math 6A
1 Chapter 4 The while loop and boolean operators Samuel Marateck ©2010.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
10-6 Solving Quadratic Equations by Factoring
Properties of Exponents
Control Structures Selections Repetitions/iterations
Project 6: Working with If Statements Essentials for Design JavaScript Level One Michael Brooks.
Addition 1’s to 20.
25 seconds left…...
Test B, 100 Subtraction Facts
Methods of Proofs October 20, A Good Proof State your plan Avoid excessive symbols Simplify as much as possible Good notation 2.
Finite-state Recognizers
Week 1.
Selection Victor Norman CS104 Calvin College. Reading Quiz Counts toward your grade.
Types of selection structures
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
A number of MATLAB statements that allow us to control the order in which statements are executed in a program. There are two broad categories of control.
5-5: Quadratic Equations
L6:CSC © Dr. Basheer M. Nasef Lecture #6 By Dr. Basheer M. Nasef.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 8 Fruitful Functions 05/02/09 Python Mini-Course: Day 2 - Lesson 8 1.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
1 Lecture 7:Control Structures I (Selection) Introduction to Computer Science Spring 2006.
Intro to Robots Conditionals and Recursion. Intro to Robots Modulus Two integer division operators - / and %. When dividing an integer by an integer we.
Decision Structures and Boolean Logic
Conditional Control Flow Constructs. Sequential Control Flow Execution order follows the textual order straight line flow Many simple problems can not.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Fall, 2006Selection1 Choices, Choices, Choices! Selection in FORTRAN Nathan Friedman Fall, 2006.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 7 Conditionals and Loops 4/18/09 Python Mini-Course: Day 2 - Lesson 7.
1 Interactive Applications (CLI) and Math Interactive Applications Command Line Interfaces The Math Class Flow of Control / Conditional Statements The.
Python Conditionals chapter 5
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 If’s – The Basic Idea “Program” for hubby: take out garbage.
5 While-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming.
3 Basics © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming.
Midterm Exam Topics (Prof. Chang's section) CMSC 201.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Based on slides by Shawn.
CNG 140 C Programming (Lecture set 3)
© 2010 David A Watt, University of Glasgow
Topics The if Statement The if-else Statement Comparing Strings
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Control Structures I (Selection)
Class 12.
Summary Two basic concepts: variables and assignments Basic types:
15-110: Principles of Computing
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Chapter 3: Selection Structures: Making Decisions
Class 13 function example unstring if if else if elif else
Presentation transcript:

4 If-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming

4-2 If-statements: basic form  An if-statement enables a program to choose between alternative courses of action.  The basic form of if-statement is: if expression : body 1 else: body 0 a sequence of statements  To execute this if-statement: 1. Evaluate expression to either True or False. 2. If the result was True, execute body If the result was False, execute body 0.

4-3 Example: maximum of two numbers  If max were not a built-in function, we could define it ourselves: def max (x, y): # Return the greater of the numbers x and y. if x > y: return x else: return y

4-4 If-statements: form without else  Sometimes one of the alternatives of an if- statement is to do nothing.  We can omit the else part: if expression : body  To execute this if-statement: 1. Evaluate expression to either True or False. 2. If the result was True, execute body If the result was False, do nothing.

4-5 Example: sorting two numbers  The following program takes two numbers in x and y, and sorts them so that the smaller number is in x and the larger in y : x = input('Enter a number: ') y = input('Enter another number: ') if x > y: # Swap the numbers in x and y … z = x x = y y = x print 'Sorted numbers:', x, y

4-6 If-statements: extended form (1)  Sometimes an if-statement has three (or more) alternatives.  We can use an extended form of if-statement: if expression 1 : body 1 elif expression 2 : body 2 else: body 0 may be replicated as often as you need may be omitted

4-7 If-statements: extended form (2)  This is equivalent to: if expression 1 : body 1 else: if expression 2 : body 2 else: body 0

4-8 Example: roots of quadratic equation (1)  Consider the general quadratic equation: ax 2 + bx + c = 0  Its roots are given by: ( ‒ b ± √(b 2 – 4ac)) / (2a)  But note that: –there are two real roots if b 2 – 4ac > 0 –there is only one real root if b 2 – 4ac = 0 –there are no real roots if b 2 – 4ac < 0.

4-9 Example: roots of quadratic equation (2)  Function: def roots (a, b, c): # Return the real root(s) of the quadratic equation # a x 2 + b x + c = 0, or ( ) if it has no real roots. d = b**2 – 4*a*c if d > 0: s = square_root(d) r1 = (-b+s)/(2*a) r2 = (-b-s)/(2*a) return (r1, r2) elif d == 0: return –b/(2*a) else: return ()

4-10 Example: roots of quadratic equation (3)  Function calls: roots(1.0, 2.0, 1.0) returns ‒ 1.0 roots(1.0, 3.0, 1.0) returns ( ‒ 0.382, ‒ 2.618) roots(1.0, 1.0, 1.0) returns ( )

4-11 Example: roots of quadratic equation (4)  Tracing the function call roots(1.0, 2.0, 1.0) : abc Enter the function: Execute “ d = b**2 - … ”: d 0.0 Test “ d > 0 ”: yields False Test “ d == 0 ”: yields True Execute “ return –b/(2*a) ”: returns ‒

4-12 Testing non-boolean values  Uniquely, Python allows a value of any type to be tested in an if-statement (or while-statement). TypeValue treated as False Values treated as True integer0non-zero integers floating-point0.0non-zero numbers string‘’ (empty string)non-empty strings listempty listnon-empty lists dictionaryempty dictionarynon-empty dict’s

4-13 Example: testing strings  Here is part of a simple command-line program. It accepts commands “duck” and “dive”, and rejects an invalid command. com = raw_input('Command? ') if com == 'duck': duck() elif com == 'dive': dive() elif com: print '- invalid command!'  This assumes that functions duck and dive actually execute the respective commands. alternatively, elif com != '':

4-14 Conditional expressions  A conditional expression evaluates its result in one of two alternative ways, depending on a boolean.  It has the form: expression 1 if expression 0 else expression 2  To evaluate this conditional expression: 1. Evaluate expression 0 to either True or False. 2. If the result was True, evaluate expression If the result was False, evaluate expression 2.

4-15 Example: conditional expression (1)  Here are shorter implementations of the abs and max functions: def abs (x): # Return the absolute value of the number x. return (x if x >= 0 else -x) def max (x, y): # Return the greater of the numbers x and y. return (x if x > y else y)  It is good practice to parenthesise this form of expression.

4-16 Boolean operators revisited  Consider an expression of the form “A and B”. –A is evaluated first. If it yields False, the overall result must be False, so B is not evaluated at all. –Thus “A and B” is equivalent to “B if A else False ”.  Similarly, consider an expression of the form “A or B”. –A is evaluated first. If it yields True, the overall result must be True, so B is not evaluated at all. –Thus “A or B” is equivalent to “ True if A else B”.

4-17 Short-circuit evaluation  The boolean operators “ and ” and “ or ” each uses short-circuit evaluation. The right operand is evaluated only if it can affect the overall result.  No other Python operator uses short-circuit evaluation. The left and right operands are both evaluated.

4-18 Example: short-circuit evaluation (1)  This function tests whether a student is qualified to graduate with an ordinary degree: def qualified (credits, grade_points): # Return True if the student has at least 360 credits # and a grade-point average of at least 9.0. return credits >= 360 and grade_points/credits >= 9.0  If the student has 0 credits, this function correctly returns False.  Short-circuit evaluation is essential here, otherwise the function would fail (division by 0).

4-19 Example: short-circuit evaluation (2)  This function uses a conditional expression to give the same result: def qualified (credits, grade_points): # Return True if the student has at least 360 credits # and a grade-point average of at least 9.0. return (grade_points/credits >= 9.0 \ if credits >= 360 \ else False)