EECS 110: Lec 11: Indefinite Loops and Program Design Aleksandar Kuzmanovic Northwestern University

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

EasyGUI “Probably the Easiest GUI in the world”. Assumptions (Teachers’ Notes) This resources sets out an introduction to using easyGUI and Python
Top-Down Design CSC 161: The Art of Programming Prof. Henry Kautz 9/16/2009.
 2002 Prentice Hall. All rights reserved Control Structures 3 control structures –Sequential structure Built into Python –Selection structure The.
Computer Science 1620 Loops.
COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Introduction to Python
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
An Introduction to Textual Programming
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Line Continuation, Output Formatting, and Decision Structures CS303E: Elements of Computers and Programming.
Programming for Linguists An Introduction to Python 24/11/2011.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
While Loops Indefinite Iteration. Last lesson we looked at definite loops using the ‘For’ statement. The while loop keeps going while some condition is.
More While Loop Examples CS303E: Elements of Computers and Programming.
CS 108 Computing Fundamentals Notes for Thursday, February 19, 2015.
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
IS 313: Putting loops to work for you What's next? [ 1, 11, 21, 1211, , ? ] [ -35, -24, -13, -2, 9, 20, 31, ? ] [ 2, 22, 222, ? ] [ 26250, 5250,
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
EECS 110: Lec 11: Indefinite Loops and Program Design Aleksandar Kuzmanovic Northwestern University
For loops in programming Assumes you have seen assignment statements and print statements.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Last Week if statement print statement input builtin function strings and methods for loop.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
Input and typing trouble! print 'Please input a number of meters' meters = input() # get input from user cm = meters * 100 # convert to centimeters print.
Designing While Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Data Types and Conversions, Input from the Keyboard CS303E: Elements of Computers and Programming.
Iteration. Iteration: Review  If you wanted to display all the numbers from 1 to 1000, you wouldn’t want to do this, would you? Start display 1 display.
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
Data Types and Conversions, Input from the Keyboard If you can't write it down in English, you can't code it. -- Peter Halpern If you lie to the computer,
EECS 110: Lec 9: Review for the Midterm Exam Aleksandar Kuzmanovic Northwestern University
CS 127 Exceptions and Decision Structures. Exception Handling This concept was created to allow a programmer to write code that catches and deals with.
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
SEQUENCES:STRINGS,LISTS AND TUPLES. SEQUENCES Are items that are ordered sequentially and accessible via index offsets into its set of elements. Examples:
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (while) Outline 3.7The While Repetition.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
EECS 110: Lec 12: Mutable Data
Week of 12/12/16 Test Review.
Introduction to Python
Data Types and Conversions, Input from the Keyboard
Line Continuation, Output Formatting, and Decision Structures
EECS 110: Lec 11: Indefinite Loops and Program Design
Engineering Innovation Center
Line Continuation, Output Formatting, and Decision Structures
Input and typing trouble!
Validations and Error Handling
Chapter 3 – Control Structures
Structured Program Development in C
3. Decision Structures Rocky K. C. Chang 19 September 2018
Python Basics with Jupyter Notebook
EPSII 59:006 Spring 2004.
Iteration – While Loops
Presentation transcript:

EECS 110: Lec 11: Indefinite Loops and Program Design Aleksandar Kuzmanovic Northwestern University

Final Exam When: –Wednesday 6/3/09 Where: –Ann. Hall G15 Time: –10AM – 11:30AM

Input and typing trouble! print 'Please input a number of meters' meters = raw_input() # get input from user cm = meters * 100 # convert to centimeters print 'That is', cm, 'cm.' # print out the result

Input and typing trouble! print 'Please input a number of meters' meters = raw_input() # get input from user cm = meters * 100 # convert to centimeters print 'That is', cm, 'cm.' # print out the result >>> Please input a number of meters 5 That is cm. What is python thinking ?!?

Fix #1: use a type converter print 'Please input a number of meters' meters = int(raw_input()) cm = meters * 100 print 'That is', cm, 'cm.' check out my newly installed int converter! The type of variable (box) matters! name: meters type: int name: cm type: int 1 100

Fix #1: use a type converter print 'Please input a number of meters' meters = int(raw_input()) # get int input from user cm = meters * 100 print 'That is', cm, 'cm.' print 'Please input a number of meters' meters = float(raw_input()) # get float input from user cm = meters * 100 print 'That is', cm, 'cm.' str converts to string type

Fix #2: use input() print 'Please input a number of meters' meters = input() # get processed input from user cm = meters * 100 print 'That is', cm, 'cm.' Why not ALWAYS use input() ?

Fix #2: use input() print 'Please input a number of meters' meters = input() # get processed input from user cm = meters * 100 print 'That is', cm, 'cm.' Why not ALWAYS use input() ? raw_input always returns input as a string! input processes the input as if typed into Python both allow you to input a prompt string

input vs. raw_input reply = raw_input( 'Enter a string and I\'ll tell you what I see.' ) for c in reply: print 'I see a(n) ', c interprets what the user types as a string of characters reply = input( 'Enter any list and I\'ll tell you what I see.' ) for c in reply: print 'I see a(n) ', c processes what the user types just as python would

More with Loopy thinking s ='gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ? How could we find the number of 'a' s ? How about 'a' s or 't' s? How could we find the number of 'ta' s ?

Loopy thinking s ='gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ? How could we find the number of 'a' s ? How about 'a' s or 't' s? How could we find the number of 'ta' s ?

Loopy thinking s ='gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ? How could we find the number of 'a' s ? How about 'a' s or 't' s? How could we find the number of 'ta' s ? s = 'gattacaaggtaaaatgca' N = 0 for i in range(0,len(s)): if s[i] == 'a': N = N + 1 print 'N is', N

Loopy thinking s = 'gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ? How could we find the number of 'a' s ? How about 'a' s or 't' s? How could we find the number of 'ta' s ?

Loopy thinking s = 'gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ? How could we find the number of 'a' s ? How about 'a' s or 't' s? How could we find the number of 'ta' s ? s = 'gattacaaggtaaaatgca' N = 0 for i in range(0,len(s)): if s[i] == 'a' or s[i] == 't': N = N + 1 print 'N is', N

Loopy thinking s ='gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ? How could we find the number of 'a' s ? How about 'a' s or 't' s? How could we find the number of 'ta' s ?

Loopy thinking s ='gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ? How could we find the number of 'a' s ? How about 'a' s or 't' s? How could we find the number of 'ta' s ? s = 'gattacaaggtaaaatgca' N = 0 for i in range(1,len(s)): if s[i] == 'a' and s[i-1] == 't': N = N + 1 print 'N is', N

Loopy thinking s ='gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ? How could we find the number of 'a' s ? How about 'a' s or 't' s? How could we find the number of 'ta' s ? s = 'gattacaaggtaaaatgca' N = 0 for i in range(1,len(s)): if s[i] == 'a' and s[i-1] == 't': N = N + 1 print 'N is', N

Loopy thinking s ='gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ?

Loopy thinking s ='gattacaaggtaaaatgca‘ - Len of current run - Len of best run How could we find the longest sequence of 'a' s ?

Planning in "pseudocode" s ='gattacaaggtaaaatgca' Loop through the string: if we do see an 'a' if the PREVIOUS letter is NOT an 'a' if the PREVIOUS letter IS an 'a' Keep track of CurRun, MaxRun

Planning in "pseudocode" s ='gattacaaggtaaaatgca' Loop through the string: if we do see an 'a' if the PREVIOUS letter is NOT an 'a' if the PREVIOUS letter IS an 'a' Keep track of CurRun, MaxRun Start a Run! CurRun = 1 Continue our run! CurRun = CurRun + 1 Check for a new maximum…

Planning in "pseudocode" s ='gattacaaggtaaaatgca' MAX = 0 cur = 0 for i in range(0,len(s)): if s[i] == 'a': if s[i-1] != 'a': cur = 1 else: cur = cur + 1 if cur > MAX: MAX = cur print 'Max is', MAX Loop through the string: if we do see an 'a' if the PREVIOUS letter is NOT an 'a' if the PREVIOUS letter IS an 'a' Keep track of CurRun, MaxRun Start a Run! Continue our run! Check for a new maximum…

s = 'gattacaaggtaaaatgca' N = 0 for i in range(0,len(s)): if s[i] == 'a': N = N + 1 print 'N is', N s = 'gattacaaggtaaaatgca' N = 0 for i in range(1,len(s)): if s[i] == 'a' and s[i-1] == 't': N = N + 1 print 'N is', N s = 'gattacaaggtaaaatgca' MAX = 0 cur = 0 for i in range(0,len(s)): if s[i] == 'a': if s[i-1] != 'a': cur = 1 else: cur = cur + 1 if cur > MAX: MAX = cur print 'Max is', MAX s = 'gattacaaggtaaaatgca' N = 0 for i in range(0,len(s)): if s[i] == 'a' or s[i] == 't': N = N + 1 print 'N is', N Summary

Loops forwhile definite iteration indefinite iteration For a known number of iterations For an unknown number of iterations

def menu(): choice = 1 # Anything except 9 while choice != 9: print "I see danger in your future..." printMenu() choice = input("Make your choice ") print "The inner eye can see no more" def printMenu(): print "What would you like to do?" print "\t 0: See another prediction" print "\t 9: Quit" Seeing into the future… " \t " represents a tab

def menu(): while True: print "I see danger in your future..." printMenu() choice = input("Make your choice ") if choice == 9: break print "The inner eye can see no more" def printMenu(): print "What would you like to do?" print "\t 0: See another prediction" print "\t 9: Quit" Gimme a break break stops the execution of the current loop I'll figure out later how to get out of this loop! OK – I'll stop the loop now and continue with the code after the loop

Indefinite Loops + input A problem this week ask you to repeatedly interact with the user (TTSecurities) What would you like to do? 0: Enter a new list 1: Print the current list 2: Find the average 9: Quit Please enter your choice The user's choice controls what happens

def menu(): choice = 1 while choice != 9: printMenu() choice = input("Please enter your choice ") if choice == 0: print "You chose to enter a new list" elif choice == 1: print "You chose to print the list" elif choice == 2: print "You chose to find this average of the list" elif choice != 9: print "You made an invalid choice" print "Goodbye!" def printMenu(): print "What would you like to do?" print "\t 0: Enter a new list" print "\t 1: Print the current list" print "\t 2: Find the average" print "\t 9: Quit" Indefinite Loops + input

if vs elif def menu(): choice = 1 while choice != 9: printMenu() choice = input("Please enter your choice ") if choice == 0: print "You chose to enter a new list" if choice == 1: print "You chose to print the list" if choice == 2: print "You chose to find this average of the list" if choice != 9: print "You made an invalid choice" print "Goodbye!" What happens if we change the elif s to if s?

Indefinite Loops + input def menu(): choice = 1 L = [] while choice != 9: printMenu() choice = input("Please enter your choice ") if choice == 0: L = getNewList() elif choice == 1: printList(L) elif choice == 2: averageList(L) elif choice != 9: print "You made an invalid choice" print "Goodbye!" def getNewList(): print "You chose to get a new list" return [] Making a function for each choice makes the code cleaner and easier to modify

Gimme another break def menu(): choice = 1 L = [] while True: printMenu() choice = input("Please enter your choice ") if choice == 0: L = getNewList() elif choice == 1: printList(L) elif choice == 2: averageList(L) elif choice == 9: break else: print "You made an invalid choice" print "Goodbye!"

The Price Is Right! Goal: Buy from a set of 5 items (as many of each as you want) while spending between $9.25 and $10.00.

Step 1: Identify Information To Store What information does this program need to keep track of?

Step 1: Identify Information To Store How much has the user spent? float: money Which items are available? list of strings: items How much does each available item cost? list of floats: prices Which item did the user currently choose? int: choice How many of the currently chosen item does the user want? int: number

Step 1: Identify Information To Store How much has the user spent? float: money Which items are available? [“coke”, “ramer”] list of strings: items How much does each available item cost? list of floats: prices Which item did the user currently choose? int: choice How many of the currently chosen item does the user want? int: number

Step 1: Identify Information To Store How much has the user spent? float: money Which items are available? [“coke”, “ramer”] list of strings: items How much does each available item cost? list of floats: prices [ 0.75, 0.25] Which item did the user currently choose? int: choice How many of the currently chosen item does the user want? int: number

Step 2: Break Down Functionality What are the things that this program needs to do?

Step 2: Break Down Functionality Control the overall game play Prompt the user to enter a choice and number of items Calculate the total spent Figure out when the game is over Figure out win or lose Print a welcome message Remove the purchased item from the lists (items, prices)

Attempt 1 def playTry1(): print "Welcome to the price is right!" print "Your goal is to buy 5 or fewer items (any number of each)" print "and spend between $9.25 and $10" items = ["bleach","coke","ramen","ice cream","super ball"] prices = [1.35,.75,.25, 3.00, 1.75] money = 0.0 while money 0: print "You have spent $", money printItems( items ) choice = input( "Which item would you like to buy? ") number = input( "How many "+items[choice]+" would you like?") print items[choice], "is $", prices[choice] money += prices[choice]*number prices = prices[0:choice] + prices[choice+1:] items = items[0:choice] + items[choice+1:] print "You have spent $", money if money >= 9.25 and money <= 10.0: print "You win!" else: print "You lose!"

"Quiz" part 1: Print Items >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0 : coke 1 : pepsi 2 : sprite

Attempt 1 def playTry1(): print "Welcome to the price is right!" print "Your goal is to buy 5 or fewer items (any number of each)" print "and spend between $9.25 and $10" items = ["bleach","coke","ramen","ice cream","super ball"] prices = [1.35,.75,.25, 3.00, 1.75] money = 0.0 while money 0: print "You have spent $", money printItems( items ) choice = input( "Which item would you like to buy? ") number = input( "How many "+items[choice]+" would you like?") print items[choice], "is $", prices[choice] money += prices[choice]*number prices = prices[0:choice] + prices[choice+1:] items = items[0:choice] + items[choice+1:] print "You have spent $", money if money >= 9.25 and money <= 10.0: print "You win!" else: print "You lose!"

Attempt 1: Issues def playTry1(): print "Welcome to the price is right!" print "Your goal is to buy 5 or fewer items (any number of each)" print "and spend between $9.25 and $10" items = ["bleach","coke","ramen","ice cream","super ball"] prices = [1.35,.75,.25, 3.00, 1.75] money = 0.0 while money 0: print "You have spent $", money printItems( items ) choice = input( "Which item would you like to buy? ") number = input( "How many "+items[choice]+" would you like?") print items[choice], "is $", prices[choice] money += prices[choice]*number prices = prices[0:choice] + prices[choice+1:] items = items[0:choice] + items[choice+1:] print "You have spent $", money if money >= 9.25 and money <= 10.0: print "You win!" else: print "You lose!" Magic numbers!

Attempt 1a def playTry1a(): LIMIT_MIN = 9.25 LIMIT_MAX = items = ["bleach","coke","ramen","ice cream","super ball"] prices = [1.35,.75,.25, 3.00, 1.75] money = 0.0 print "Welcome to the price is right!" print "Your goal is to buy", len(items), "or fewer items…" print "and spend between $", LIMIT_MIN, "and $", LIMIT_MAX while money 0: print "You have spent $", money printItems( items ) choice = input( "Which item would you like to buy? ") number = input( "How many "+items[choice]+" would you like?") print items[choice], "is $", prices[choice] money += prices[choice]*number prices = prices[0:choice] + prices[choice+1:] items = items[0:choice] + items[choice+1:] print "You have spent $", money if money >= LIMIT_MIN and money <= LIMIT_MAX: print "You win!" else: print "You lose!"

def playTry1a(): LIMIT_MIN = 9.25 LIMIT_MAX = items = ["bleach","coke","ramen","ice cream","super ball"] prices = [1.35,.75,.25, 3.00, 1.75] money = 0.0 print "Welcome to the price is right!" print "Your goal is to buy", len(items), "or fewer items…" print "and spend between $", LIMIT_MIN, "and $", LIMIT_MAX while money 0: print "You have spent $", money printItems( items ) choice = input( "Which item would you like to buy? ") number = input( "How many "+items[choice]+" would you like?") print items[choice], "is $", prices[choice] money += prices[choice]*number prices = prices[0:choice] + prices[choice+1:] items = items[0:choice] + items[choice+1:] print "You have spent $", money if money >= LIMIT_MIN and money <= LIMIT_MAX: print "You win!" else: print "You lose!" Attempt 1a: Issue Functionality is not broken out

def playBetter(): """ Play the game """ [items, prices] = initilizeItems() LIMIT_HIGH = LIMIT_LOW = 9.25 money = 0.0 printIntro(LIMIT_LOW, LIMIT_HIGH, items) while not allDone(items, LIMIT_LOW, money): print "You have spent $", money [items, prices, spent] = playRound(items, prices) money += spent winOrLose(money, LIMIT_LOW, LIMIT_HIGH) Each function does one specific thing. It's clear where we go to change aspects of the game. Code is self-commenting. Functions can return more than one thing in a list

def playRound(items, prices): """ Play one round of the game Inputs: A list of items and a list of prices Returns: [items, prices, spent] where items is list of items remaining, prices is a list of remaining prices, and spent is the amount spent this round""" print "*********************" printItems( items ) choice = input( "Which item would you like to buy? ") number = input( "How many " + items[choice] + " would you like? ") print items[choice], "is $", prices[choice] spent = prices[choice]*number prices = prices[0:choice] + prices[choice+1:] items = items[0:choice] + items[choice+1:] return [items, prices, spent]

def playBetter(): """ Play the game """ [items, prices] = initilizeItems() LIMIT_HIGH = LIMIT_LOW = 9.50 money = 0.0 printIntro(LIMIT_LOW, LIMIT_HIGH, items) while not allDone(items, LIMIT_LOW, money): print "You have spent $", money [items, prices, spent] = playRound(items, prices) money += spent winOrLose(money, LIMIT_LOW, LIMIT_HIGH) You CAN (and should) modify your code as you go to make it cleaner and better organized. (That is, you don’t have to get it perfect the first time)

>>> diff([7, 0, 6, 4]) 1 "Quiz" Print a list of strings with the specified format def diff( L ): Return the min difference between any 2 elements in L You need determine each element's index… Example: You can assume at least 2 elements in the list Only consider unsigned differences. >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0 : coke 1 : pepsi 2 : sprite def printItems( items ): Name(s):_______________________________ Hint: use a NESTED loop

"Quiz" part 1: Print Items >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0 : coke 1 : pepsi 2 : sprite

"Quiz" part 1: Print Items >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0 : coke 1 : pepsi 2 : sprite def printItems(items): for x in range(len(items)): print x,”:”,items[x]

"Quiz" part 1: Print Items >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0:coke 1:pepsi 2:sprite def printItems(items): for x in range(len(items)): print str(x)+”:”+items[x]

>>> diff([7, 0, 6, 4]) 1 "Quiz" Part 2 def diff( L ): Return the min difference between any 2 elements in L Example: You can assume at least 2 elements in the list Only consider unsigned differences. Hint: use a NESTED loop

>>> diff([7, 0, 6, 4]) 1 "Quiz" Part 2 def diff( L ): mindif = abs(L[1] – L[0]) for i in range(len(L)-1): for j in range(i+1,len(L)): d = abs(L[i]-L[j]) if d < mindiff: mindiff = d return mindif Return the min difference between any 2 elements in L Example: You can assume at least 2 elements in the list Only consider unsigned differences. Hint: use a NESTED loop