Conditional Execution

Slides:



Advertisements
Similar presentations
What type of data can a variable hold?
Advertisements

Nested if-else Statements.  Should be indented to make the logic clear.  Nested statement executed only when the branch it is in is executed. For example,
Selection Victor Norman CS104 Calvin College. Reading Quiz Counts toward your grade.
Flow of Control Usually the order of statement execution through a method is linear: one after another flow of control: the order statements are executed.
Python Programming Language
Conditional Statements Introduction to Computing Science and Programming I.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Decision Making George Mason University. Today’s topics 2 Review of Chapter 2: Decision Making Go over exercises Decision making in Python.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Geography 465 Assignments, Conditionals, and Loops.
Intro to Robots Conditionals and Recursion. Intro to Robots Modulus Two integer division operators - / and %. When dividing an integer by an integer we.
INTRODUCTION TO PYTHON PART 3 - LOOPS AND CONDITIONAL LOGIC CSC482 Introduction to Text Analytics Thomas Tiahrt, MA, PhD.
Loops and Iteration Chapter 5 Python for Informatics: Exploring Information
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
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.
Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 4 Decision.
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Conditional Execution Chapter 3 Python for Informatics: Exploring Information
Decision Making CMSC 201. Overview Today we will learn about: Boolean expressions Decision making.
Chapter Making Decisions 4. Relational Operators 4.1.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
CONDITIONALS. Boolean values Boolean value is either true or false It is name after the British mathemetician, George Boole who first formulated Boolean.
Decisions in Python Boolean functions. A Boolean function This is a function which returns a bool result (True or False). The function can certainly work.
An Object-Oriented Approach to Programming Logic and Design Chapter 5 Making Decisions.
September 7, 2004ICP: Chapter 3: Control Structures1 Introduction to Computer Programming Chapter 3: Control Structures Michael Scherger Department of.
8. DECISION STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Decision Making CMSC 201 Chang (rev ).
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.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 5 Making Decisions.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
Types, Truth, and Expressions Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
 Type Called bool  Bool has only two possible values: True and False.
Control Flow (Python) Dr. José M. Reyes Álamo.
CS0007: Introduction to Computer Programming
Conditional Execution
Introduction to Python
Chapter 4: Making Decisions.
Python: Control Structures
Operator Precedence Operators Precedence Parentheses () unary
Topics The if Statement The if-else Statement Comparing Strings
Conditional Execution
Topics The if Statement The if-else Statement Comparing Strings
Selection CIS 40 – Introduction to Programming in Python
Arithmetic operations, decisions and looping
Python - Conditional Execution
Computers & Programming Languages
Conditional Execution
Conditional Execution
3. Decision Structures Rocky K. C. Chang 19 September 2018
Selection Statements.
Python Programming Language
Boolean Expressions to Make Comparisons
Relational Operators.
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
CHAPTER 5: Control Flow Tools (if statement)
Control Statements.
Decision Structures Zelle - Chapter 7
Presentation transcript:

Conditional Execution Chapter 3 Python for Informatics: Exploring Information www.py4inf.com

Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License. http://creativecommons.org/licenses/by/3.0/. Copyright 2010- Charles R. Severance

Conditional Steps Yes Program: x = 5 if x < 10: Output: print 'Smaller’ if x > 20: print 'Bigger' print 'Finis' print 'Smaller' Output: Smaller Finis X > 20 ? Yes print 'Bigger' print 'Finis'

Remember: “=” is used for assignment. Comparison Operators Boolean expressions ask a question and produce a Yes or No result which we use to control program flow Boolean expressions using comparison operators evaluate to - True / False - Yes / No Comparison operators look at variables but do not change the variables Python Meaning < Less than <= Less than or Equal == Equal to >= Greater than or Equal > Greater than != Not equal Remember: “=” is used for assignment. http://en.wikipedia.org/wiki/George_Boole

Comparison Operators x = 5 if x == 5 : print 'Equals 5' if x > 4 : print 'Greater than 4’ if x >= 5 : print 'Greater than or Equal 5' if x < 6 : print 'Less than 6' if x <= 5 : print 'Less than or Equal 5’ if x != 6 : print 'Not equal 6' Equals 5 Greater than 4 Greater than or Equal 5 Less than 6 Less than or Equal 5 Not equal 6

One-Way Decisions x = 5 Yes print 'Before 5’ if x == 5 : print 'Is 5’ print 'Is Still 5’ print 'Third 5’ print 'Afterwards 5’ print 'Before 6’ if x == 6 : print 'Is 6’ print 'Is Still 6’ print 'Third 6’ print 'Afterwards 6' X == 5 ? Yes Before 5 Is 5 Is Still 5 Third 5 Afterwards 5 Before 6 Afterwards 6 print 'Is 5' No print 'Still 5' print 'Third 5' One-Way Decisions

Indentation Increase indent indent after an if statement or for statement (after : ) Maintain indent to indicate the scope of the block (which lines are affected by the if/for) Reduce indent to back to the level of the if statement or for statement to indicate the end of the block Blank lines are ignored - they do not affect indentation Comments on a line by themselves are ignored w.r.t. indentation

Warning: Turn Off Tabs Most text editors can turn tabs into spaces - make sure to enable this feature NotePad++: Settings -> Preferences -> Language Menu/Tab Settings TextWrangler: TextWrangler -> Preferences -> Editor Defaults Python cares a *lot* about how far line is indented. If you mix tabs and spaces, you may get “indentation errors” even if everything looks fine Please do this now while you are thinking about it so we can all stay sane...

This will save you much unnecessary pain.

increase / maintain after if or for decrease to indicate end of block blank lines and comment lines ignored x = 5 if x > 2 : # comments print 'Bigger than 2' # don’t matter print 'Still bigger' # but can confuse you print 'Done with 2' # if you don’t line # them up x = 5 if x > 2 : print 'Bigger than 2' print 'Still bigger' print 'Done with 2' for i in range(5) : print i if i > 2 : print 'Done with i', i

Mental begin/end squares x = 5 if x > 2 : # comments print 'Bigger than 2' # don’t matter print 'Still bigger' # but can confuse you print 'Done with 2' # if you don’t line # them up x = 5 if x > 2 : print 'Bigger than 2' print 'Still bigger' print 'Done with 2' for i in range(5) : print i if i > 2 : print 'Done with i', i

Nested Decisions x = 42 if x > 1 : print 'More than one' yes print 'More than one' no x = 42 if x > 1 : print 'More than one' if x < 100 : print 'Less than 100' print 'All done' x < 100 yes no print 'Less than 100' print 'All Done'

Nested Decisions x = 42 if x > 1 : print 'More than one' yes print 'More than one' no x = 42 if x > 1 : print 'More than one' if x < 100 : print 'Less than 100' print 'All done' x < 100 yes no print 'Less than 100' print 'All Done'

Nested Decisions x = 42 if x > 1 : print 'More than one' yes print 'More than one' no x = 42 if x > 1 : print 'More than one' if x < 100 : print 'Less than 100' print 'All done' x < 100 yes no print 'Less than 100' print 'All Done'

Two Way Decisions x > 2 Sometimes we want to do one thing if a logical expression is true and something else if the expression is false It is like a fork in the road - we must choose one or the other path but not both x > 2 no yes print 'Not bigger' print 'Bigger' print 'All Done'

Two-way using else : x = 4 if x > 2 : print 'Bigger' else : no yes x = 4 if x > 2 : print 'Bigger' else : print 'Smaller' print 'All done' print 'Smaller' print 'Bigger' print 'All Done'

Two-way using else : x = 4 if x > 2 : print 'Bigger' else : no yes x = 4 if x > 2 : print 'Bigger' else : print 'Smaller' print 'All done' print 'Smaller' print 'Bigger' print 'All Done'

Multi-way if x < 2 : print 'Small' elif x < 10 : print 'Medium' yes x < 2 print 'Small' if x < 2 : print 'Small' elif x < 10 : print 'Medium' else : print 'LARGE' print 'All done' no x<10 yes print 'Medium' no print 'LARGE' print 'All Done'

Multi-way x = 0 if x < 2 : print 'Small' elif x < 10 : yes x < 2 print 'Small' x = 0 if x < 2 : print 'Small' elif x < 10 : print 'Medium' else : print 'LARGE' print 'All done' no x<10 yes print 'Medium' no print 'LARGE' print 'All Done'

Multi-way x = 5 if x < 2 : print 'Small' elif x < 10 : yes x < 2 print 'Small' x = 5 if x < 2 : print 'Small' elif x < 10 : print 'Medium' else : print 'LARGE' print 'All done' no x<10 yes print 'Medium' no print 'LARGE' print 'All Done'

Multi-way x = 20 if x < 2 : print 'Small' elif x < 10 : yes x < 2 print 'Small' x = 20 if x < 2 : print 'Small' elif x < 10 : print 'Medium' else : print 'LARGE' print 'All done' no x<10 yes print 'Medium' no print 'LARGE' print 'All Done'

Multi-way if x < 2 : print 'Small' elif x < 10 : print 'Medium' print 'Big' elif x< 40 : print 'Large' elif x < 100: print 'Huge' else : print 'Ginormous' # No Else x = 5 if x < 2 : print 'Small' elif x < 10 : print 'Medium' print 'All done'

Multi-way Puzzles if x < 2 : print 'Below 2' elif x < 20 : else : print 'Something else' Which will never print? if x < 2 : print 'Below 2' elif x >= 2 : print 'Two or more' else : print 'Something else'

The try / except Structure You surround a dangerous section of code with try and except. If the code in the try works - the except is skipped If the code in the try fails - it jumps to the except section

$ cat notry.py astr = 'Hello Bob’ istr = int(astr) print 'First', istr astr = '123’ print 'Second', istr $ python notry.py Traceback (most recent call last): File "notry.py", line 2, in <module> istr = int(astr)ValueError: invalid literal for int() with base 10: 'Hello Bob' All Done

$ cat notry.py astr = 'Hello Bob’ istr = int(astr) print 'First', istr astr = '123’ print 'Second', istr $ python notry.py Traceback (most recent call last): File "notry.py", line 2, in <module> istr = int(astr)ValueError: invalid literal for int() with base 10: 'Hello Bob' The program stops here All Done

Generic Computer Software Input Devices Central Processing Unit Secondary Memory Who has see a traceback in CTools? Output Devices Main Memory

$ cat tryexcept.py astr = 'Hello Bob' try: istr = int(astr) except: print 'First', istr astr = '123' print 'Second', istr When the first conversion fails - it just drops into the except: clause and the program continues. $ python tryexcept.py First -1 Second 123 When the second conversion succeeds - it just skips the except: clause and the program continues.

try / except astr = 'Bob' try: print 'Hello' istr = int(astr) print 'There' except: istr = -1 print 'Done', istr istr = int(astr) print 'There' istr = -1 print 'Done', istr Safety net

Sample try / except rawstr = raw_input('Enter a number:') try: ival = int(rawstr) except: ival = -1 if ival > 0 : print 'Nice work'else: print 'Not a number' $ python trynum.py Enter a number:42 Nice work Enter a number:fourtytwo Not a number $

Exercise Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours. Enter Hours: 45 Enter Rate: 10 Pay: 475.0 475 = 40 * 10 + 5 * 15

Exercise Rewrite your pay program using try and except so that your program handles non-numeric input gracefully. Enter Hours: 20 Enter Rate: nine Error, please enter numeric input Enter Hours: forty

Summary Comparison operators == <= >= > < != Logical operators: and or not Indentation One Way Decisions Two way Decisions if : and else : Nested Decisions Multiway decisions using elif Try / Except to compensate for errors