Guide to Programming with Python

Slides:



Advertisements
Similar presentations
A8 – Control Structures if, if-else, switch Control of flow in Java Any sort of complex program must have some ability to control flow.
Advertisements

I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Conditional Statements Introduction to Computing Science and Programming I.
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
Chapter 2: Algorithm Discovery and Design
Program Design and Development
Fundamentals of Python: From First Programs Through Data Structures
The University of Texas – Pan American
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Fundamentals of Python: First Programs
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Guide to Programming with Python Chapter Three Branching, while Loops, and Program Planning: The Guess My Number Game.
Invitation to Computer Science, Java Version, Second Edition.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Mastery Objective: Students will understand how to use while loops in computer programming.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Course A201: Introduction to Programming 09/16/2010.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
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)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter 2: Algorithm Discovery and Design Invitation to Computer Science.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
JavaScript Controlling the flow of your programs with ‘if’ statements
Control Flow (Python) Dr. José M. Reyes Álamo.
Recap: If, elif, else If <True condition>:
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II (Repetition)
Introduction to Python
Repetition (While-Loop) version]
Python: Control Structures
Lesson 05: Iterations Class Chat: Attendance: Participation
Programming Mehdi Bukhari.
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
CS 115 Lecture 8 Structured Programming; for loops
Lecture 07 More Repetition Richard Gesick.
2008/09/24: Lecture 6b CMSC 104, Section 0101 John Y. Park
Beginning C Lecture 4 Lecturer: Dr. Zhao Qinpei
Lecture 4B More Repetition Richard Gesick
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Control Structures - Repetition
Arithmetic operations, decisions and looping
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Lesson 05: Iterations Topic: Introduction to Programming, Zybook Ch 4, P4E Ch 5. Slides on website.
Structured Program
Iteration: Beyond the Basic PERFORM
Iteration: Beyond the Basic PERFORM
3 Control Statements:.
Chapter 3 – Control Structures
IST256 : Applications Programming for Information Systems
Chapter 5 Loops.
Chapter 4 Selection.
3. Decision Structures Rocky K. C. Chang 19 September 2018
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Flowcharts and Pseudo Code
CHAPTER 6: Control Flow Tools (for and while loops)
For loops Taken from notes by Dr. Neil Moore
EPSII 59:006 Spring 2004.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

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: print "Access Granted” 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 condtion1 condtion2 condition1 and condition2 True False 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 condition not condition True False 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 condtion1 condtion2 condition1 or condition2 True False 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 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 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 Repetition based on a condition 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 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 Like while 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 for i in range(10): print i, # counting by fives for i in range(0, 50, 5): # counting backwards for i in range(10, 0, -1): 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