Conditional Execution

Similar documents
Conditional Execution

Python - Conditional Execution

Decision Structures Zelle - Chapter 7

STEAM Clown Productions. Python - Conditional. STEAM Clown & Productions Copyright 2018 STEAM Clown. Last Updated: Thursday, January 24, 2019.

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

Computing with Numbers Zelle - Chapter 3

Python for Informatics

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

Variables, Expressions, and Statements

Decision Structures CSC1310. Python Programming, 2/e 1

Stored (and reused) Steps

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

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

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

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

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

Programming for Engineers in Python. Autumn

cs1114 REVIEW of details test closed laptop period

Introduction to Python (All the Basic Stuff)

Control Structures in Java if-else and switch

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science

Control Structures 1 / 17

Class extension and. Exception handling. Genome 559

CPSC 217-T03/T08. Functions Ruting Zhou

Exception Handling. Genome 559

Flow Control: Branches and loops

Week - 01 Lecture - 04 Downloading and installing Python

Racket Style Guide Fall 2017

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

Introduction to Computer Programming for Non-Majors

Functions and Decomposition

Text Input and Conditionals

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Python for Non-programmers

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Programming for Engineers in Python. Recitation 1

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

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Ch.2: Loops and lists

Computational Expression

STEAM Clown Productions. Python-Functions. Page 1

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Introduction to Computer Programming for Non-Majors

Visualize ComplexCities

Why Program? Computers want to be helpful... Programmers Anticipate Needs. Chapter 1. Computers are built for one purpose - to do things for us

CMSC 201 Fall 2018 Lab 04 While Loops

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

Introduction to Computer Programming for Non-Majors

The Big Python Guide

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

Introduction to Computer Programming for Non-Majors

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

Lists, loops and decisions

MA 1128: Lecture 02 1/22/2018

1 Getting used to Python

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

QUIZ Friends class Y;

Premium POS Pizza Order Entry Module. Introduction and Tutorial

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

Python Lists. What is not a Collection. A List is a kind of Collection. friends = [ 'Joseph', 'Glenn', 'Sally' ]

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Chapter 4: Making Decisions

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Getting started with the Spyder IDE

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

Chapter 4: Making Decisions

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

The first program: Little Crab

5. Control Statements

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Math Day 2 Programming: How to make computers do math for you

CMSC 201 Computer Science I for Majors

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

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

These are notes for the third lecture; if statements and loops.

CS Summer 2013

LOOPS. Repetition using the while statement

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras

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

Introduction to Python. Dmytro Karpenko Research Infrastructure Services Group, Department for Research Computing, USIT, UiO

If Statements, For Loops, Functions

CMSC201 Computer Science I for Majors

A Little Python Part 1. Introducing Programming with Python

MITOCW watch?v=kz7jjltq9r4

CSE 142 Su 04 Computer Programming 1 - Java. Objects

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

Python workshop. Week 2: Make choices and reuse code.

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Scripting Languages. Python basics

Algorithms and Programming I. Lecture#12 Spring 2015

Chapter 4 The If Then Statement

Transcription:

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

Unless otherwise ted, 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

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

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 Python Meaning < Less than <= Less than or Equal == Equal to >= Greater than or Equal > Greater than!= Not equal Comparison operators look at variables but do t change the variables http://en.wikipedia.org/wiki/george_boole Remember: = is used for assignment.

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' Comparison Operators Equals 5 Greater than 4 Greater than or Equal 5 Less than 6 Less than or Equal 5 Not equal 6

x = 5 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' Before 5 No Is 5 Is Still 5 Third 5 Afterwards 5 Before 6 Afterwards 6 X == 5? Yes print 'Is 5' 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 igred - they do t affect indentation Comments on a line by themselves are igred 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 w 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 igred x = 5 x = 5 if x > 2 : if x > 2 : # comments print 'Bigger than 2' print 'Still bigger' print 'Bigger than 2' print 'Done with 2' # don t matter print 'Still bigger' for i in range(5) : # but can confuse you print i if i > 2 : print 'Done with 2' print 'Bigger than 2' # if you don t line print 'Done with i', i # them up

Mental begin/end squares 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 'Bigger than 2' print 'Done with i', i 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

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

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

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

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

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

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

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

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

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

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

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

Multi-way Puzzles Which will never print? if x < 2 : print 'Below 2' elif x >= 2 : print 'Two or more' else : print 'Something else' if x < 2 : print 'Below 2' elif x < 20 : print 'Below 20' elif x < 10 : print 'Below 10' 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 try.py astr = 'Hello Bob istr = int(astr) print 'First', istr astr = '123 istr = int(astr) print 'Second', istr $ python try.py Traceback (most recent call last): File "try.py", line 2, in <module> istr = int(astr) ValueError: invalid literal for int() with base 10: 'Hello Bob' All Done

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

Input Devices Software Central Processing Unit Secondary Memory Generic Computer Output Devices Main Memory

$ cat tryexcept.py astr = 'Hello Bob' try: istr = int(astr) except: istr = -1 print 'First', istr astr = '123' try: istr = int(astr) except: istr = -1 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. print 'Second', istr

try / except astr = 'Bob' astr = 'Bob' try: print 'Hello' istr = int(astr) print 'There' except: istr = -1 print 'Hello' istr = int(astr) print 'There' istr = -1 print 'Done', istr 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 $ python trynum.py 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 n-numeric input gracefully. Enter Hours: 20 Enter Rate: nine Error, please enter numeric input Enter Hours: forty Error, please enter numeric input

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