Iteration  Iteration just means we keep doing the same thing over and over until some threshold is reached, until a condition has been met.  We’ve already.

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

While loops.
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.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Loops – While, Do, For Repetition Statements Introduction to Arrays
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.
Python Programming: An Introduction To Computer Science
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Making Decisions In Python
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Python Programming: An Introduction To Computer Science
The University of Texas – Pan American
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Decision Structures and Boolean Logic
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
CPS120 Introduction to Computer Science Iteration (Looping)
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
Chapter 5 Loops.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
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.
Control Structures RepetitionorIterationorLooping Part I.
CPS120 Introduction to Computer Science Iteration (Looping)
Xiaojuan Cai Computational Thinking 1 Lecture 8 Loop Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
James Tam Making Decisions In Python In this section of notes you will learn how to have your programs choose between alternative courses of action.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
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.
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.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
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.
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.
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.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Python: Control Structures
ECS10 10/10
Topics The if Statement The if-else Statement Comparing Strings
JavaScript: Control Statements.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Logical Operators and While Loops
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Topics The if Statement The if-else Statement Comparing Strings
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Outline Altering flow of control Boolean expressions
CS190/295 Programming in Python for Life Sciences: Lecture 6
子夜吳歌 ~ 李白 長安一片月, 萬戶擣衣聲; 秋風吹不盡, 總是玉關情。 何日平胡虜, 良人罷遠征。
子夜吳歌 ~ 李白 長安一片月, 萬戶擣衣聲; 秋風吹不盡, 總是玉關情。 何日平胡虜, 良人罷遠征。
Logical Operators and While Loops
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Iteration  Iteration just means we keep doing the same thing over and over until some threshold is reached, until a condition has been met.  We’ve already seen a definite or counted loop: for i in range(15):

# average1.py # A program to average a set of numbers # Illustrates counted loop with accumulator def main(): n = input("How many numbers do you have? ") sum = 0.0 for i in range(n): x = input("Enter a number >> ") sum = sum + x print "\nThe average of the numbers is", sum / n main()

 A definite or counted loop assumes we know or can control exactly how many times the loop is executed. In the example for x in range(10) we supply the number of iterations—10.  But there are times when we, the programmers, won’t know how many iterations we need.  For these instances, we use indefinite or conditional loops.

 The generic form of the conditional loop uses the while keyword…. while :  The is a Boolean statement, as with decision/selection structures.  while i <= 10:for i in range(11) print iprint i i = i + 1 These are equivalent

 Here are a few important things to remember as you work with while loops:  Initialize your index value before you start the while loop  Make sure your index value will at some point meet the condition  Don’t forget to increment the index value

 Here’s what I mean: i = 0 while i <= 10: print i  This code will continue indefinitely, because the value of i never changes. Hence i will never exceed 10, thus violating the condition and ending the loop. This is an INFINITE LOOP.

 On the other hand, if you fail to initialize your index value, or initialize it so that it can never meet the condition, the loop will likely never happen at all.  while i <= 10: print i i = i + 1  i = 16 while i <= 10: print i i = i + 1 In this case, since i is never assigned an initial value, the loop just won’t happen. In this case, i is assigned a value that already violates the condition—so the loop never happens

 The example we’ve been looking at assumes we, the programmers, set the number of iterations, e.g., i <= 10. But sometimes we want the user to determine how many iterations there are.  Here’s the algorithm:  set continue? to Yes  while continue? = yes  get first piece of data  process that piece of data  if there is more data, don’t change continue?  otherwise, set continue? to No

 For example, if we wanted to ask the user for the prices of things he/she wanted to buy, then add them up, we could use an interative loop:  cont= “y” total = 0.0 while cont == “y”: v = input(“Enter a price: “) total = total + v cont = raw_input(“To continue, type ‘y’; to quit, type ‘n’) print total

# average2.py # A program to average a set of numbers # Illustrates interactive loop with two accumulators def main(): moredata = "yes" sum = 0.0 count = 0 while moredata[0] == 'y': x = input("Enter a number >> ") sum = sum + x count = count + 1 moredata = raw_input("Do you have more numbers (yes or no)? ") print "\nThe average of the numbers is", sum / count main()

 Instead of asking the user BOTH if she/he wants to continue AND to enter another value, programmers often use sentinel values, which just means that if users enter a special value instead of a regular data item, the loop ends and the program is over. Usually that sentinel value is a negative number, since we commonly ( when we ask users for values) want positive values from our users.

 Here’s the syntax that would offer the user the option to enter a real piece of data or a special value to quit (usually it’s a negative number to quit):  num = input(“Enter a number, or a negative number to quit”)

# average3.py # A program to average a set of numbers # Illustrates sentinel loop using negative input as sentinel def main(): sum = 0.0 count = 0 x = input("Enter a number (negative to quit) >> ") while x >= 0: sum = sum + x count = count + 1 x = input("Enter a number (negative to quit) >> ") print "\nThe average of the numbers is", sum / count main() Notice that the index value, x, is initialized BEFORE the while loop starts

 If we wanted to be able to include negative numbers in our program, using a sentinel value which is negative wouldn’t work. It would be better to just ask the user to hit the key without a value.  We can do this if we use raw_input() to get a string; if the string is empty the loop quits. If the string exists (if the user has typed in a number), we can use the eval() function to successfully apply arithmetic.

# average4.py # A program to average a set of numbers # Illustrates sentinel loop using empty string as sentinel def main(): sum = 0.0 count = 0 xStr = raw_input("Enter a number ( to quit) >> ") while xStr != "": x = eval(xStr) sum = sum + x count = count + 1 xStr = raw_input("Enter a number ( to quit) >> ") print "\nThe average of the numbers is", sum / count main()

 Of course, it would be easier to import a file with all the scores already entered. Earlier, we used a definite loop to read through the lines in a file; the stop condition was neatly determined by the Python syntax: infile = open(fileName, ‘r’) for line in infile:

 We can also use a while loop, but in this case we need to be able to designate the end of the file to stop the loop.  In this case, the while loop is used to read one line of the file after another, and to process the data in each line. When the end of the file is reached, the loop stops.  The loop does not stop at blank lines in the file because there is an invisible control symbol \n

 Here’s the code for a while loop that will stop at the end of the file:  infile = open(fileName, ‘r’) nuline = infile.readline() while nuline != “”: #process the line nuline = infile.readline()

# average6.py # Computes the average of numbers listed in a file. def main(): fileName = raw_input("What file are the numbers in? ") infile = open(fileName,'r') sum = 0.0 count = 0 line = infile.readline() while line != "": sum = sum + eval(line) count = count + 1 line = infile.readline() print "\nThe average of the numbers is", sum / count if __name__ == '__main__': main()

 Often we have to work through a file that contains data on each line that must be processed one by one. To do this, we want nested loops. The outer loop works through the file, line by line; the inner loop performs repetitive work on the data within one line.

 # a program demonstrating nested for loops  def main():  index = 0  for y in range(5):  for x in range(4):  print 'In the "nested" for loop:', index, x, y  index += 1 # This adds one to index  main()

# average7.py # Computes the average of numbers listed in a file. # Works with multiple numbers on a line. import string def main(): fileName = raw_input("What file are the numbers in? ") infile = open(fileName,'r') sum = 0.0 count = 0 line = infile.readline() while line != "": for xStr in string.split(line, ","): sum = sum + eval(xStr) count = count + 1 line = infile.readline() print "\nThe average of the numbers is", sum / count if __name__ == '__main__': main()

 Sometimes simple conditional expressions don’t accomplish what we need done. If we try to use simple conditional expressions with decision statements, it can get really messy and cumbersome.  The solution is to combine conditional expressions into more complex expressions. To do this we need Boolean operators.

 If we wanted to grant awards for GPAs between certain ranges, we might need Boolean operators. For example, imagine this scheme:  So, grades between 4.0 and 3.8 get the Poobah; between 3.8 and 3.5, the Nabob; and between 3.5 and 3.3, the Enchilada. GPA Award Up to 4.0Greater than 3.8Poobah 3.8 or lessGreater than 3.5Nabob 3.5 or lessGreater than 3.3Enchilada

 If we put together two conditions using a Boolean operator, we can come up with one condition: GPA = input(“Please enter your GPA”) if GPA 3.8 print “you’ve won the Poobah!” elif GPA 3.5 print “you’ve won the Nabob!” elif GPA 3.3 print “you’ve won the Enchilada!” else print “Sorry, no cigar.”

 Notice that if we make any changes in this code—for example, if we change elif GPA 3.5 to elif GPA = 3.5 then a GPA of 3.5 would qualify for both the Nabob and Enchilada awards.  The moral: when setting up Boolean conditions, pay close attention to “boundary conditions”, and test for those to make sure you get the results you want.

OperatorFunction and (binary)Both conditions must be true for the whole expression to be true or (binary)Only one condition must be true for the whole expression to be true not (unary)The whole expression is true only if the one condition is false Arithmetic OperatorFunction ==equal to >=greater than or equal to <=less than or equal to >greater than <less than !=not equal to

 The example we just looked at: Condition1Condition2Whole expression True False TrueFalse If GPA is:Condition1: GPA <= 4.0 Condition2: GPA > 3.8 Whole expression 3.87True 3.80TrueFalse 4.0True 3.6TrueFalse

 The example we just looked at: Condition1Condition2Whole expression True FalseTrue FalseTrue False If GPA is:Condition1: GPA <= 4.0 Condition2: GPA > 3.8 Whole expression 3.87True 3.80TrueFalseTrue 4.0True 3.6TrueFalseTrue

 not is an unary operator, which means it works on just one condition, not on two condition, like the binary operators and & or. The truth table for not is very simple: Condition1Whole expression TrueFalse True Condition1: GPA > 3.5Whole expression TrueFalse True

 A racquetball game can end when either play reaches a score of 15.  If we were to write a code fragment to express this, it would look like this: while not (playerA == 15 or playerB == 15) #continue playing  The combined or statement will evaluate as true if either player reaches 15; but they will not continue playing if this is true.

 Here’s another condition: the racquetball game stops if either player reaches 15 OR the score is 7-0.  In code: scoreA == 15 or scoreB == 15 or (scoreA == 7 and scoreB == 0) or (scoreB == 7 and scoreA == 0)  Because we are linking each expression with a Boolean or, if any one of the conditions is true, the whole expression is true.

 In volleyball, one team must reach 15 AND win by at least two points.  To do this in code:  (scoreA >= 15 and scoreA-scoreB >= 2) or (scoreB >= 15 and scoreB –scoreA >= 2  Or, even more condensed:  (scoreA >= 15 or scoreB >= 15) and abs(scoreA –scoreB) >= 2

 There are parallels between Boolean rules and the laws of simple algebra. For example  Hence 0 evaluates as false in computer languages, and 1 evaluates as true. Also, and is similar to multiplication and or is similar to addition. a * 0 = 0a and false = = false a * 1 = aa and true == a a + 0 = aa or false == a

 Three more things about Boolean algebra:  A double negative cancels out: not (not a) == a or !(not a) == a  Distribution: a or (b and c) == (a or b) and (a or c) a and (b or c) == (a and b) or (a and c)  DeMorgan’s laws: not(a or b) == (not a) and (not b) not(a and b) == (not a) or (not b)

 Essentially, input validation tests what the user has entered, and if it’s not a valid entry, then the program keeps asking for a valid entry until the user provides one.  This is particularly useful when using a sentinel value to control a loop—for example, if the user enters a negative number the loop stops.  In order to make this work, the user has to enter a value in the loop.

 In other words, the loop starts, then the user is prompted for an entry, the entry value is tested, and if it is valid, the loop continues; otherwise, the user is reprompted.  userData = -1 while userData <0:  userData = input(“Enter a GPA”) if userData < 0: print “Enter a positive number”

 Python provides a keyword, break, to suddenly exit a loop. This can be used in a validity check.  while True: userData = input(“Enter your GPA”) if userData >= 0: break print “Enter a positive number”

 Python 2.3 supports a bool data type, which evaluates as to either false or true. False is interpreted as zero, true usually as 1, but in fact any number other than 0 will evaluate as true.  In the case of strings, any string that is not empty can be evaluated as true. An empty string will be evaluated as false.

 Because Python has loose data typing (meaning that the programmer doesn’t have to explicitly designate data types, and a variable can change data types on assignment), a string variable can be evaluated as a bool data type.  response = raw_input(“Enter your class: SR, JR, SO, FR”) if response: # in other words, if response is true, that is not empty classRank = response else: classRank = “SR”