380 likes | 511 Views
Guide to Programming with Python. Chapter Three Control the Flow (Branching, while/for Loops, and Program Planning); The Guess My Number Game. Objectives. Make choices based on conditions – to selectively execute certain portions of the code Use if to execute code based on a condition
E N D
Guide to Programming with Python Chapter Three Control the Flow (Branching, while/for Loops, and Program Planning); The Guess My Number Game
Objectives • Make choices based on conditions – to selectively execute certain portions of the code • Use if to execute code based on a condition • Use if-else to make a choice based on a condition • Use if-elif-else structures to make a choice based on a series of conditions • Repeat parts of a program • While/for loop • Use break to break the loop • Use continue to jump back to the top of a loop • Plan programs Guide to Programming with Python
The M & Ms Question Reminder color = raw_input("Input color: ") Color = color.lower() if color == “yellow" or color == "orange": print color, "--- What you hate" elif color == "red": print color, "--- Favorite Food" elif color == "blue": print color, "--- Favorite Movie and why" else: print "unknown color" print color, "--- A random fact about yourself" Guide to Programming with Python
Using Indentation to Create Blocks Correct: if password == "secret": print "Access Granted" else: print "Access Denied” Incorrect: if password == "secret": print "Access Granted” else: print "Access Denied" Guide to Programming with Python
Conditions • Condition: Expression that is True or False • True and False are values of type boolean • password == "secret" is condition - True or False • If variable password is equal to string "secret" condition evaluates to True • Otherwise, condition evaluates to False • The password program • Often create conditions by comparing values Guide to Programming with Python
Comparison Operators Table 3.1: Useful comparison operators Guide to Programming with Python
Treating Values as Conditions • Any value can be interpreted as True or False when used as condition • Any empty (None) or zero value is False • So, 0, "", and None are False • Any other value is True • So for example, -10, 2.5, "banana" are True • if money: • money is treated as condition • True when money not 0; False when money is 0 Guide to Programming with Python
Using Compound Conditions • Can create more complex conditions by joining simple conditions seen so far with logical operators to create a compound condition • Simple condition: A simple form of a condition, such as a single comparison • Logical operator: An operator (and, or, not) that joins conditions to form a large condition • Compound condition: A larger condition formed by joining simpler conditions Guide to Programming with Python
The and Logical Operator • Like “and” in English, means both • True only if both conditions are True Guide to Programming with Python
The and Logical Operator (continued) if username == "M.Dawson" and password == "secret": print "Hi, Mike." • Condition created by and is only True if both simpler conditions are True • So if both username is equal to "M.Dawson" and password is equal to "secret“, then greeting is displayed • Otherwise, it’s not displayed Guide to Programming with Python
The not Logical Operator • Evaluates to opposite • Like “not” in English Guide to Programming with Python
The not Logical Operator (continued) username = "" while not username: username = raw_input("Username: ") • not username is True while username equal to "" • while loop prompts until user enters something other than empty string • At that point, not username is False and loop ends Guide to Programming with Python
The or Logical Operator • Like “or” in English, means either • True when either condition is True Guide to Programming with Python
The or Logical Operator elif username == "guest" or password == "guest": print "Welcome, guest." • Condition created by or is True when either simpler condition is True • So if either username is equal to "guest" or password is equal to "guest", then greeting is displayed • Otherwise, it’s not displayed Guide to Programming with Python
Precedence of Logical Operators A or B and C A and B or C and D A and B and C or D not A and B or C See an example first: logical_fun.py A or (B and C) (A and B) or (C and D) ((A and B) and C) or D ((not A) and B) or C Logical operators have precedence that determines how things are grouped in the absence of parentheses High Medium Low not and or Use parentheses to make logic clearer Guide to Programming with Python
Branching Structures Branches based on a condition/conditions A block of code Guide to Programming with Python
The Password Guess Program • GuessPwDemoFlow.py • if-structure • if-else structure • if-elif-else structure Guide to Programming with Python
The Mood Computer Program if mood == 0: print "I am happy" elif mood == 1: print "I am OK" elif mood == 2: print "I am sad" else: print "Illegal mood value!” The Mood Computer Program Guide to Programming with Python
Looping Structure:The Three-Year-Old Simulator Program Figure 3.8: Sample run of Three-Year-Old Simulator program If you’ve ever been in charge of a three-year-old… Guide to Programming with Python
The while Loop while condition: <block> while response != "Because.": response = raw_input("Why? ”) • Repetition based on a condition • Allows you to repeat section of code as long as some condition is True • Like if statement, in that it tests a condition and executes associated block if condition True • But, after block, repeats condition test; if condition still True, repeats block • Continues process until condition tests False Guide to Programming with Python
The while Loop (continued) • Sentry variable: Variable used in loop condition • response • Loop body: Block associated with loop • response = raw_input(”Why? ") • Infinite loop: A loop that will never end; considered a logical error • A type of infinite loop where sentry variable is never updated is easy to track down • But there are more insidious forms of the never-ending loop (The Losing Battle Program) Guide to Programming with Python
Fixing an Infinite Loop while health != 0: trolls += 1 health = health – damage • Problem is condition is False only when health is exactly 0 • Tracing: Examining the execution of a program and its internal values in single steps • Tracing shows that health becomes negative, but never exactly 0 • Problem solved with new condition: health > 0 Guide to Programming with Python
Creating Intentional Infinite Loops • “Intentional infinite” loop • Has condition that’s always True • But not truly infinite • Written with an exit condition in loop body • Sometimes cleaner to write than alternative loop Guide to Programming with Python
The break Statement while True: count += 1 # end loop if count is greater than 10 if count > 10: break • while True: creates an “intentionally infinite” loop • Must provide a way for loop to end • break causes a loop to end immediately • Create while True: loop if cleaner than alternative • Avoid break when possible, can lead to confusion Guide to Programming with Python
The continue Statement while True: count += 1 # end loop if count is greater than 10 if count > 10: break # skip 5 if count == 5: continue print count • continue jumps to top of loop to check condition • Avoid when possible, can lead to confusion • Can you rewrite the finicky counter to avoid break and continue? Guide to Programming with Python
Using for Loops • for loop • Likewhile loop, repeats a loop body • Unlike while loop, doesn’t repeat based on condition • Repeats loop body for each element in a sequence • Ends when it reaches end of the sequence • e.g., go through sequence of game titles and print each Guide to Programming with Python
Counting Forward, By Fives, and Backwards # counting forward for i in range(10): print i, # counting by fives for i in range(0, 50, 5): print i, # counting backwards for i in range(10, 0, -1): print i, Guide to Programming with Python
Understanding for Loops • Sequence: An ordered list of elements • Element: A single item in a sequence • Iterate: To move through a sequence, in order • List of your top-ten movies • A sequence • Each element is a movie title • To iterate over would be to go through each title, in order • More on for loops later Guide to Programming with Python
The Guess My Number Game Figure 3.1: Sample run of the Guess My Number game Got it in only three guesses! Try to beat that. Guide to Programming with Python
Generating Random Numbers • Unpredictability adds excitement to games • Great for simulations • “Random” numbers generated by computer not truly random • Pseudorandom: generated by formula; complex but predictable pattern • Need to use a module (random) • import random Guide to Programming with Python
randrange()Function • randrange() generates random number from range • If pass single integer n, randrange() returns random number from 0 to n - 1 • randrange() part of random module • Module: file that contains code meant to be used in other programs • random is like a toolbox • randrange() is like a tool in the toolbox Guide to Programming with Python
randrange()Function (continued) • Use import statement to gain access to a module • import random • Now can access randrange() via random • random.randrange(6) #returns random num 0 – 5 • dot notation: Convention used for accessing part of an object • Like the possessive in English • random.randrange() is like saying “The random module’s randrange() function” Guide to Programming with Python
Program Planning • Saves time (and heartache) later • Algorithm: Set of clear, easy-to-follow instructions for accomplishing some task • Stepwise refinement: Process used to rewrite algorithms in more detail so that they’re ready for implementation • Pseudocode: Outline of a program written in something between English and a programming language Guide to Programming with Python
Algorithm in Pseudocode The Make a Million Dollars Algorithm if you can think of a new and useful product then that’s your product otherwise repackage an existing product as your product make an infomercial about your product show the infomercial on TV charge $100 per unit of your product sell 10,000 units of your product Guide to Programming with Python
Applying Stepwise Refinement create an infomercial about your product Becomes: write a script for an infomercial about your product rent a TV studio for a day hire a production crew hire an enthusiastic audience film the infomercial Guide to Programming with Python
Summary • Branching structure • if • if-else • if-elif-else • The while/for loop repeats a block of code as long as a condition is…? • True • break & continue • Conditions (simple conditions, compound conditions) • When used as a condition, any value can be interpreted as…? • True or False • A block of code: A section of code indented to form a single unit is called…? • A module is a file that contains code meant to be used in other programs • use import <module_name> Guide to Programming with Python