Python - Loops and Iteration

Slides:



Advertisements
Similar presentations
While loops.
Advertisements

How SAS implements structured programming constructs
CHAPTER 5: Repetition Control Structure. Objectives  To develop algorithms that use DOWHILE and REPEAT.. UNTIL structures  Introduce a pseudocode for.
CS0004: Introduction to Programming Repetition – Do Loops.
Python for Informatics: Exploring Information
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
Introducing Loop Statements Liang, pages Loop statements control repeated execution of a block of statements Each time the statements in the block.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Loops and Iteration Chapter 5 Python for Informatics: Exploring Information
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Mastery Objective: Students will understand how to use while loops in computer programming.
If statements while loop for loop
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
Loops Robin Burke IT 130. Outline Announcement: Homework #6 Conditionals (review) Iteration while loop while with counter for loops.
CPS120 Introduction to Computer Science Iteration (Looping)
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Repetition Control Structure. Introduction Many applications require certain operations to be carried out more than once. Such situations require repetition.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 10 Iteration: Loops 05/02/09 Python Mini-Course: Day 3 - Lesson 10 1.
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.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Loops and Iteration Chapter 5 Python for Informatics: Exploring Information
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
1 Looping Chapter 6 2 Getting Looped in C++ Using flags to control a while statement Trapping for valid input Ending a loop with End Of File condition.
Loop Structures and Booleans Zelle - Chapter 8 Charles Severance - Textbook: Python Programming: An Introduction to Computer Science,
Follow up from lab See Magic8Ball.java Issues that you ran into.
REPETITION CONTROL STRUCTURE
Python Loops and Iteration
Chapter 5: Control Structures II
Introduction To Repetition The for loop
Lecture 6 Repetition Richard Gesick.
Loops and Iteration Chapter 5 Python for Everybody
Python: Control Structures
Lesson 05: Iterations Class Chat: Attendance: Participation
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.
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Control Structures II (Repetition)
Repetition-Counter control Loop
While Loops in Python.
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.
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.
Lecture 4A Repetition Richard Gesick.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Iteration with While You can say that again.
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.
Loop Structures and Booleans Zelle - Chapter 8
Algorithm Discovery and Design
ICT Programming Lesson 3:
A LESSON IN LOOPING What is a loop?
CHAPTER 6: Control Flow Tools (for and while loops)
Logical Operators and While Loops
Introduction to Computer Science
Repetition Statements (Loops) - 2
PROGRAM FLOWCHART Iteration Statements.
While Loops in Python.
Presentation transcript:

Python - Loops and Iteration

Repeated Steps No Yes Program: Output: n = 5 while n > 0 : print n n = n – 1 print 'Blastoff!' print n 5 4 3 2 1 Blastoff! print n n = n -1 print 'Blastoff' Loops (repeated steps) have iteration variables, which change each time through a loop. Often these iteration variables go through a sequence of numbers.

An Infinite Loop No Yes n = 5 print 'Lather' print 'Rinse' n = 5 while n > 0 : print 'Lather’ print 'Rinse' print 'Dry off!' print 'Dry off!' What is wrong with this loop?

n = 0 Another Loop No Yes n > 0 ? print 'Lather' print 'Rinse' n = 0 while n > 0 : print 'Lather’ print 'Rinse' print 'Dry off!' print 'Dry off!' What does this loop do?

Breaking Out of a Loop -- The break statement ends the current loop and jumps to the statement immediately following the loop while True: line = raw_input('> ') if line == 'done' : break print line print 'Done!' > hello there hello there > finished finished > done Done!

Breaking Out of a Loop -- The break statement ends the current loop and jumps to the statement immediately following the loop while True: line = raw_input('> ') if line == 'done' : break print line print 'Done!' > hello there hello there > finished Finished > done Done!

while True: line = raw_input('> ') if line == 'done' : No Yes True ? break print line print 'Done!' .... break ... print 'Done'

Finishing an Iteration with continue -- The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration while True: line = raw_input('> ') if line[0] == '#' : continue if line == 'done' : break print line print 'Done!' > hello there hello there > # don't print this > print this! print this! > done Done!

Finishing an Iteration with continue -- The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration while True: line = raw_input('> ') if line[0] == '#' : continue if line == 'done' : break print line print 'Done!' > hello there hello there > # don't print this > print this! print this! > done Done!

line = raw_input('> ’) if line[0] == '#' : continue No True ? Yes while True: line = raw_input('> ’) if line[0] == '#' : continue if line == 'done' : break print line print 'Done!' .... .... continue ... ... print 'Done'

Indefinite Loops -- While loops are called "indefinite loops" because they keep going until a logical condition becomes False -- The loops discussed so far are pretty easy to examine to see if they will terminate or if they will be "infinite loops“

Definite Loops -- Often there is a list of items in a file - effectively a finite set of things -- Write a loop to run for each of the items in a set using the Python for construct -- These loops are called "definite loops" because they execute an exact number of times -- "definite loops iterate through the members of a set"

A Simple Definite Loop 5 4 3 2 1 Blastoff! for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!'

A Definite Loop with Strings friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends : print 'Happy New Year:', friend print 'Done!' Happy New Year: Joseph Happy New Year: Glenn Happy New Year: Sally Done!

A Simple Definite Loop Done? Move i ahead No Yes 5 4 3 2 1 Blastoff! for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!' print i print 'Blast off!' Definite loops (for loops) have explicit iteration variables that change each time through a loop. These iteration variables move through the sequence or set.

Looking at In... for i in [5, 4, 3, 2, 1] : print i -- The iteration variable “iterates” though the sequence (ordered set) -- The block (body) of code is executed once for each value in the sequence -- The iteration variable moves through all of the values in the sequence Five-element sequence Iteration variable for i in [5, 4, 3, 2, 1] : print i

Done? Move i ahead No Yes -- The iteration variable “iterates” though the sequence (ordered set) Done? Move i ahead print i -- The block (body) of code is executed once for each value in the sequence -- The iteration variable moves through all of the values in the sequence for i in [5, 4, 3, 2, 1] : print i

Done? Move i ahead No Yes for i in [5, 4, 3, 2, 1] : print i i = 5

The Loop: What We Do in Loops Note: Even though these examples are simple, the patterns apply to all kinds of loops

Making “smart” loops for thing in data: Set some variables to initial values for thing in data: Look for something or do something to each entry separately, updating a variable. Look at the variables.

Looping through a Set $ python basicloop.py Before 9 41 12 3 74 15 After print 'Before' for thing in [9, 41, 12, 3, 74, 15] : print thing print 'After'

What is the Largest Number?

What is the Largest Number? 4 1 1 2 7 1 4 5 3 9 -13 4174 largest_so_far

Counting in a Loop $ python countloop.py zork = 0 Before 0 1 9 2 41 3 12 4 3 5 74 6 15 After 6 print 'Before', zork for thing in [9, 41, 12, 3, 74, 15] : zork = zork + 1 print zork, thing print 'After', zork To count how many times we execute a loop we introduce a counter variable, which starts at 0 and we add one to it each time through the loop

Summing in a Loop $ python countloop.py zork = 0 Before 0 9 9 50 41 62 12 65 3 139 74 154 15 After 154 print 'Before', zork for thing in [9, 41, 12, 3, 74, 15] : zork = zork + thing print zork, thing print 'After', zork To add up a value we encounter in a loop, we introduce a sum variable that starts at 0 and we add the value to the sum each time through the loop

Finding the Average in a Loop $ python averageloop.py Before 0 0 1 9 9 2 50 41 3 62 12 4 65 3 5 139 74 6 154 15 After 6 154 25 count = 0 sum = 0 print 'Before', count, sum for value in [9, 41, 12, 3, 74, 15] : count = count + 1 sum = sum + value print count, sum, value print 'After', count, sum, sum / count An average just combines the counting and sum patterns and divides when the loop is done

Filtering in a Loop print 'Before’ $ python search1.py Before for value in [9, 41, 12, 3, 74, 15] : if value > 20: print 'Large number',value print 'After' $ python search1.py Before Large number 41 Large number 74 After We use an if statement in the loop to catch / filter the values we are looking for.

Search Using a Boolean Variable $ python search1.py found = False Before False False 9 False 41 False 12 True 3 True 74 True 15 After True print 'Before', found for value in [9, 41, 12, 3, 74, 15] : if value == 3 : found = True print found, value print 'After', found To search and know if a value was found - a variable starts at False and is set to True as soon as the value is found

What is the Smallest Number? 4 1 1 2 7 1 4 5 9 3 -1 smallest_so_far

What is the Smallest Number? 4 1 1 2 7 1 4 5 9 3 None 9 3 largest_so_far

Finding the smallest value smallest = None print 'Before’ for value in [9, 41, 12, 3, 74, 15] : if smallest is None : smallest = value elif value < smallest : smallest = value print smallest, value print 'After', smallest $ python smallest.py Before 9 9 9 41 9 12 3 3 3 74 3 15 After 3 Determine a smallest variable -- The first time through the loop smallest is None so the first value to be the smallest

The "is" and "is not" Operators smallest = None print 'Before’ for value in [3, 41, 12, 9, 74, 15] : if smallest is None : smallest = value elif value < smallest : smallest = value print smallest, value print 'After', smallest -- Python has an "is" operaror that can be used in logical expressions -- Implies 'is the same as' -- Similar to, but stronger than == -- 'is not' also is a logical operator