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

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

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

Flow Control: Branches and loops

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

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

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

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

REPETITION CONTROL STRUCTURE LOGO

5. Control Statements

Python for Informatics

Conditionals and Recursion. Python Part 4

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

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

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

Text Input and Conditionals

LOOPS. Repetition using the while statement

CME 193: Introduction to Scientific Python Lecture 1: Introduction

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

Learning the Language - V

Control Structures 1 / 17

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

Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -

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

cs1114 REVIEW of details test closed laptop period

The following expression causes a divide by zero error:

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

Condition Controlled Loops. Introduction to Programming - Python

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

(Python) Chapter 3: Repetition

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

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

Test #2 October 8, 2015

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

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

Chapter 4: Control Structures I (Selection)

Information Science 1

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

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

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

And Parallelism. Parallelism in Prolog. OR Parallelism

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Flow Control. CSC215 Lecture

C++ for Python Programmers

Introduction. C provides two styles of flow control:

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

CS Summer 2013

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

Chapter 8. Statement-Level Control Structures

Why Is Repetition Needed?

Part 1. Summary of For Loops and While Loops

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

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

Lecture 4 CSE July 1992

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Outline. Announcements. Homework 2. Boolean expressions 10/12/2007. Announcements Homework 2 questions. Boolean expression

9. Elementary Algebraic and Transcendental Scalar Functions

Conditional Expressions and Decision Statements

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

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

Week - 01 Lecture - 03 Euclid's Algorithm for gcd. Let us continue with our running example of gcd to explore more issues involved with program.

Information Science 1

Chapter 3. Selections

The Practice of Computing Using PYTHON

An overview about DroidBasic For Android

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

CS 106 Introduction to Computer Science I

C: How to Program. Week /Mar/05

Object-Oriented Programming

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

CS 112: Intro to Comp Prog

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

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

Python for Non-programmers

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

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

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

The Big Python Guide

Divisibility Rules and Their Explanations

3. Logical Values. Boolean Functions; the Type bool; logical and relational operators; shortcut evaluation

Names and Functions. Chapter 2

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

Built-in functions. You ve used several functions already. >>> len("atggtca") 7 >>> abs(-6) 6 >>> float("3.1415") >>>

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

Programming Paradigms

C++ Programming: From Problem Analysis to Program Design, Third Edition

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

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

Selection Statements. Pseudocode

Transcription:

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

Control: A Quick Overview 2

Selection 3

Selection Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing 4

5

6

Relational Operators Less than: < Greater than: > Equal to: == (Not the same as =) Not equal to:!= Less than or equal to: <= Greater than or equal to: >= 7

Python if Statement if boolean expression : suite evaluate the boolean (True or False) if True, execute all statements in the suite 8

Warning About Indentation Elements of the suite must all be indented the same number of spaces/tabs Python only recognizes suites when they are indented the same distance You must be careful to get the indentation right to get suites right. 9

Python Selection, Round 2 if boolean expression: suite1 else: suite2 The process is: evaluate the boolean if True, run suite1 if False, run suite2 10

Safe Lead in Basketball Algorithm due to Bill James (www.slate.com) under what conditions can you safely determine that a lead in a basketball game is insurmountable? 11

The Algorithm Take the number of points one team is ahead Subtract three Add ½ point if team that is ahead has the ball, subtract ½ point otherwise Square the result If the result is greater than the number of seconds left, the lead is safe 12

Code Listing 2.5 13

# 3. Add a half-point if the leading team has the ball, # subtract a half-point if the other team has the ball. has_ball = raw_input("does the lead team have\ the ball (Yes or No): ") if has_ball == 'Yes': points = points + 0.5 else: points = points - 0.5 14

Code Listing 2.6 15

# 3. Add a half-point if the leading team has the ball, # subtract a half-point if the other team has the ball. has_ball = raw_input("does the lead team have\ the ball (Yes or No): ") if has_ball == 'Yes': points = points + 0.5 else: points = points - 0.5 # numbers less than 0 become 0 if points < 0: points = 0 16

Code Listing 2.8 17

# 5. If the result is greater than the number of seconds # left in the game, the lead is safe. seconds = int(raw_input("enter the number of\ seconds remaining: ")) if points > seconds: print "Lead is safe." else: print "Lead is not safe." 18

Repetition: A Quick Overview 19

Repeating Statements Besides selecting which statements to execute, a fundamental need in a program is repetition repeat a set of statements under some conditions With both selection and repetition, we have the two most necessary programming statements 20

While and For Statements The while statement is the more general repetition construct. It repeats a set of statements while some condition is True. The for statement is useful for iteration, moving through all the elements of data structure, one at a time. 21

while Loop Top-tested loop (pretest) test the boolean before running test the boolean before each iteration of the loop while boolean expression: statementsuite 22

23

Repeat While the Boolean is True while loop will repeat the statements in the suite while the boolean is True (or its Python equivalent) If the boolean expression never changes during the course of the loop, the loop will continue forever. 24

Code Listing 2.10 25

# simple while x_int = 0 # initialize loop-control variable # test loop-control variable at beginning of loop while x_int < 10: print x_int, # print x_int each time x_int = x_int + 1 # change loop variable # bigger than value printed in loop! print print "Final value of x_int: ", x_int 26

General Approach to a While outside the loop, initialize the boolean somewhere inside the loop you perform some operation which changes the state of the program, eventually leading to a False boolean and exiting the loop Have to have both! 27

For and Iteration One of Python s strength s is it s rich set of built-in data structures The for statement is a common statement for manipulation of a data structure for each element in the datastructure perform some operation on that element 28

29

Perfect Number Example 30

A Perfect Number numbers and their factors were mysterious to the Greeks and early mathematicians They were curious about the properties of numbers as they held some significance A perfect number is a number whose sum of factors (excluding the number) equals the number First perfect number is: 6 (1+2+3) 31

Abundant, Deficient abundant numbers summed to more than the number. 12: 1+2+3+4+6 =16 deficient numbers summed to less than the number. 13: 1 32

Design prompt for a number for the number, collect all the factors once collected, sum up the factors compare the sum and the number and respond accordingly 33

Code Listing 2.13 Check Perfection 34

if thenum == sumofdivisors: print thenum,"is perfect" else: print thenum,"is not perfect" 35

Code Listing 2.14 Finding Factors 36

divisor = 1 sumofdivisors = 0 while divisor < thenum: if thenum % divisor==0: # divisor evenly # divides thenum sumofdivisors = sumofdivisors + divisor divisor = divisor + 1 37

Improving the Perfect Number Program Work with a range of numbers For each number in the range of numbers: collect all the factors once collected, sum up the factors compare the sum and the number and respond accordingly Print a summary 38

Code Listing 2.16 Examine a Range of Numbers 39

topnumstr = raw_input("what is the upper\ topnum = int(topnumstr) thenum=2 while thenum <= topnum: # sum the divisors of thenum number for the range:") # classify the number based on its divisor sum thenum += 1 40

Code Listing 2.18 (Focus on Number Classification) 41

topnum = raw_input( Upper range number:") topnum = int(topnum) thenum=2 while thenum <= topnum: # sum up the divisors, see Code Listing 2.17 # classify the number based on its divisor sum if thenum == sumofdivisors: print thenum,"is perfect" if thenum < sumofdivisors: print thenum,"is abundant" if thenum > sumofdivisors: print thenum,"is deficient" thenum += 1 42

Control In Depth 43

Booleans 44

Boolean Expressions George Boole s (mid-1800 s) mathematics of logical expressions Boolean expressions (conditions) have a value of True or False Conditions are the basis of choices in a computer, and, hence, are the basis of the appearance of intelligence in them. 45

What is True, and What is False true: any nonzero number or nonempty object. 1, 100, hello, [a,b] false: a zero number or empty object. 0,, [ ] Special values called True and False, which are just standins for 1 and 0. However, they print nicely (True or False) Also a special value, None, less than everything and equal to nothing 46

Boolean Expression Every boolean expression has the form: expression booleanoperator expression The result of evaluating something like the above is also just true or false. However, remember what constitutes true or false in Python! 47

Relational Operators In Python 2.x, you can compare different types and get an answer just don t do it! Weird answers (fixed in 3.x) Relational Operators have low preference 5 + 3 < 3 2 8 < 1 False 48

Examples If the value of integer myint is 5, then the value of expression myint < 7 is True If the value of char mychar is 'A', then the value of expression mychar == 'Q' is False 49

What Does Equality Mean? Two senses of equality two variables refer to objects with the same values two variables refer to the same object. The id() function used for this. 50

51

Chained Comparisons In python, chained comparisons work just like you would expect in a mathematical expression: Given myint has the value 5 0 <= myint <= 5 True 0 < myint <= 5 > 10 False 52

Pitfall Be careful of floating point equality comparisons, especially with zero, e.g. myfloat==0. Use the converse!= whenever possible. Result = 2/2.0000000000000001 Result == 1.0 True 53

Compound Expressions Logically 0 < X < 3 is actually (0 < X) and (X < 3) Logical Operators (lower case) and or not 54

Truth Tables p q not p p and q p or q True True False False True False True False 55

Truth Tables p q not p p and q p or q True True False True False False False True True False False True 56

Truth Tables p q not p p and q p or q True True True True False False False True False False False False 57

Truth Tables p q not p p and q p or q True True True True False True False True True False False False 58

Truth Tables p q not p p and q p or q True True False True True True False False False True False True True False True False False True False False 59

Compound Evaluation Logically 0 < X < 3 is actually (0 < X) and (X < 3) Evaluate using X with a value of 5: (0< X) and (X< 3) Parenthesis first: (True) and (False) Final value: False (Note: parentheses are not necessary in this case.) 60

Precedence & Associativity Relational operators have precedence and associativity just like numerical operators. See Table 2.2 61

Booleans vs. Relationals Relational operations always return True or False Booleans are different in that: They can return values (that represent True or False) They have short circuiting 62

Remember! 0,,[ ] or other empty objects are equivalent to False anything else is equivalent to True 63

Ego Search on Google Google search uses Booleans by default, all terms are and ed together you can specify or (using OR) you can specify not (using -) Example is: Punch and ( Bill or William ) and not gates 64

65

More on Assignments 66

Remember Assignments? Format: lhs = rhs Behavior: expression in the rhs is evaluated producing a value the value produced is placed in the location indicated on the lhs 67

Can do Multiple Assignments x, y = 2, 3 # assigns x=2 and y=3 print x, y # prints 2 3 68

Swap Initial values: X is 2, Y is 3 Behavior: swap values of X and Y Note: X=Y Y=X doesn t work introduce extra variable temp temp = X // save X s value in temp X=Y // assign Y s value to X Y=temp // assign temp s value to Y 69

Swap Using Multiple Assignment x, y = 2, 3 print x, y # prints 2 3 x, y = y, x print x, y #prints 3 2 70

Chaining x = y = 5 print x, y # prints 5 5 71

More Control: Selection 72

Compound Statements Compound statements involve a set of statements being used as a group Most compound statements have: a header, ending with a : a suite of statements to be executed if, for, while are examples of compound statements 73

74

Have Seen 2 Forms of Selection if boolean expression: suite if boolean expression: suite else: suite 75

Python Selection, Round 3 if boolean expression1: suite1 elif boolean expression2: suite2 (as many elif s as you want) else: suitelast 76

if, elif, else, the Process evaluate boolean expressions until: the boolean expression returns True none of the boolean expressions return True if a boolean returns True, run the corresponding suite. Skip the rest of the if if no boolean returns True, run the else suite, the default suite 77

Code Listing 2.20 Updated Perfect Number classification 78

# classify the number based on its divisor sum if thenum == sumofdivisors: print thenum,"is perfect" elif thenum < sumofdivisors: print thenum,"is abundant" else: print thenum,"is deficient" thenum += 1 79

More Control: Repetition 80

While Loop, Round Two while loop, oddly, can have an associated else statement else statement is executed when the loop finishes under normal conditions basically the last thing the loop does as it exits 81

While with Else while booleanexpression: suite suite else: suite suite rest of the program 82

83

Break Statement A break statement in a loop, if executed, exits the loop It exists immediately, skipping whatever remains of the loop and the else statement (if it exists) of the loop 84

Code Listing 2.21 Essential Part of the Guessing Game 85

# while guess is range, keep asking while 0 <= guess <= 100: if guess > number: print "Guessed Too High." elif guess < number: print "Guessed Too Low." else: # correct guess, exit with break print "You guessed it. The number was:",number break # keep going, get the next guess guessstring = raw_input("guess a number: ") guess = int(guessstring) else: print "You quit early, the number was:",number 86

Continue Statement A continue statement, if executed in a loop, means to immediately jump back to the top of the loop and re-evaluate the conditional Any remaining parts of the loop are skipped for the one iteration when the continue was exectued 87

Code Listing 2.22 Part of the Guessing Numbers Program 88

# Stop if a period (.) is entered while thenumstr!= "." : if not thenumstr.isdigit(): # not a number, an error print "Error, only numbers please" thenumstr = raw_input("number:") continue # if the number is bad, ignore it thesum += int(thenumstr) thenumstr = raw_input("number:") 89

Change in Control: Break and Continue While loops are easiest read when the conditions of exit are clear Excessive use of continue and break within a loop suite make it more difficult to decide when the loop will exit and what parts of the suite will be executed each loop. Use them judiciously. 90

While Overview while test1: statement_list_1 if test2: break if test3: continue # more statements else: statement_list_2 # Exit loop now; skip else # Go to top of loop now # If we didn t hit a break # break or continue lines can appear anywhere 91

Range and for Loop 92

Range Function The range function generates a sequence of integers range(5) => [0, 1, 2, 3, 4] assumed to start at 0 goes up to, but does not include, the provided number argument. range(3,10) => [3, 4, 5, 6, 7, 8, 9] first argument is the number to begin with second argument is the end (not included!) 93

Iterating Through the Sequence for num in range(1,5): print num range generates the sequence [1, 2, 3, 4] for loop assigns num each of the values in the sequence, one at a time in sequence prints each number (one number per line) 94

Hailstone Example 95

Collatz The Collatz sequence is a simple algorithm applied to any positive integer In general, by applying this algorithm to your starting number you generate a sequence of other positive numbers, ending at 1 Unproven whether every number ends in 1 (though strong evidence exists) 96

Algorithm while the number does not equal one If the number is odd, multiply by 3 and add 1 If the number is even, divide by 2 Use the new number and reapply the algorithm 97

Even and Odd Use the remainder operator if num % 2 == 0: # even if num % 2 == 1: # odd if num %2: # odd (why???) 98

Code Listing 2.26 Hailstone Sequence, Loop 99

while num > 1: # stop when the sequence reaches 1 if num%2: # num is odd num = num*3 + 1 else: # num is even num = num/2 print num,",", # add num to sequence count +=1 # add to the count else: print # blank line for nicer output print "Sequence is ",count," numbers long" 100