Python for Informatics: Exploring Information

Slides:



Advertisements
Similar presentations
Python for Informatics: Exploring Information
Advertisements

While loops.
Conditional Execution
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.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
Chapter 5: Loops and Files.
Sahar Mosleh California State University San MarcosPage 1 While Loop and For Loop.
Chapter 2 Writing Simple Programs
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.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
CPS120 Introduction to Computer Science Iteration (Looping)
CPS120: Introduction to Computer Science Decision Making in Programs.
Functions Chapter 4 Python for Informatics: Exploring Information
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.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Conditional Execution Chapter 3 Python for Informatics: Exploring Information
Introduction to Loops Iteration Repetition Counting Loops Also known as.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
CPS120 Introduction to Computer Science Iteration (Looping)
Tuples Chapter 10 Python for Informatics: Exploring Information
Repetition Control Structure. Introduction Many applications require certain operations to be carried out more than once. Such situations require repetition.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
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!
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
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,
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
Chapter 5: Control Structures II
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.
CS1010 Programming Methodology
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)
While Loops in Python.
Python - Loops and Iteration
LOOPS.
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
Lecture 4A Repetition Richard Gesick.
Iteration with While You can say that again.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Conditional Execution
Loop Structures and Booleans Zelle - Chapter 8
Algorithm Discovery and Design
Chapter 3 – Control Structures
CHAPTER 6: Control Flow Tools (for and while loops)
Logical Operators and While Loops
Introduction to Computer Science
Introduction to Computer Science
While Loops in Python.
Presentation transcript:

Python for Informatics: Exploring Information Loops and Iteration Chapter 5 Python for Informatics: Exploring Information www.pythonlearn.com

Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License. http://creativecommons.org/licenses/by/3.0/. Copyright 2010- Charles Severance

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

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

Another Loop No Yes n = 0while n > 0 : print 'Lather' print 'Rinse' print 'Dry off!' print 'Lather' print 'Rinse' 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 It is like a loop test that can happen anywhere in the body of the loop > hello therehello there> finishedfinished> doneDone! while True: line = raw_input('> ') if line == 'done' : break print lineprint 'Done!'

Breaking Out of a Loop The break statement ends the current loop and jumps to the statement immediately following the loop It is like a loop test that can happen anywhere in the body of the loop > hello therehello there> finishedfinished> doneDone! while True: line = raw_input('> ') if line == 'done' : break print lineprint 'Done!'

while True: line = raw_input('> ') if line == 'done' : break print lineprint 'Done!' No Yes True ? .... break ... print 'Done' http://en.wikipedia.org/wiki/Transporter_(Star_Trek)

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 lineprint 'Done!' > hello therehello there> # don't print this> print this!print this!> doneDone!

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 lineprint 'Done!' > hello therehello there> # don't print this> print this!print this!> doneDone!

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

Indefinite Loops While loops are called "indefinite loops" because they keep going until a logical condition becomes False The loops we have seen so far are pretty easy to examine to see if they will terminate or if they will be "infinite loops" Sometimes it is a little harder to be sure if a loop will terminate

Definite Loops Quite often we have a list of items of the lines in a file - effectively a finite set of things We can write a loop to run the loop once 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 We say that "definite loops iterate through the members of a set"

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

A Simple Definite Loop friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends : print 'Happy New Year:', friend print 'Done!' Happy New Year: JosephHappy New Year: GlennHappy New Year: SallyDone!

A Simple Definite Loop No Yes 5 4 3 for i in [5, 4, 3, 2, 1] : print i Done? Move i ahead 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.

Five-element sequence Looking at In... 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

The iteration variable “iterates” though the sequence (ordered set) No Yes Done? 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 Move i ahead print i for i in [5, 4, 3, 2, 1] : print i

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

Definite Loops Quite often we have a list of items of the lines in a file - effectively a finite set of things We can write a loop to run the loop once 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 We say that "definite loops iterate through the members of a set"

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

Set some variables to initial values Making “smart” loops The trick is “knowing” something about the whole loop when you are stuck writing code that only sees one entry at a time 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.pyBefore9411237415After print 'Before' for thing in [9, 41, 12, 3, 74, 15] : print thing print 'After'

What is the Largest Number? 9 41 12 3 74 15

What is the Largest Number? 9 41 12 3 74 15 -1 9 41 74 largest_so_far

Finding the largest value $ python largest.py Before -19 941 4141 1241 374 7474 15After 74 largest_so_far = -1print 'Before', largest_so_farfor the_num in [9, 41, 12, 3, 74, 15] : if the_num > largest_so_far : largest_so_far = the_num print largest_so_far, the_numprint 'After', largest_so_far We make a variable that contains the largest value we have seen so far. If the current number we are looking at is larger, it is the new largest value we have seen so far.

Counting in a Loop $ python countloop.py Before 01 92 413 124 35 746 15After 6 zork = 0print 'Before', zorkfor thing in [9, 41, 12, 3, 74, 15] : zork = zork + 1 print zork, thingprint 'After', zork To count how many times we execute a loop we introduce a counter variable that starts at 0 and we add one to it each time through the loop.

Summing in a Loop $ python countloop.py Before 09 950 4162 1265 3139 74154 15After 154 zork = 0print 'Before', zorkfor thing in [9, 41, 12, 3, 74, 15] : zork = zork + thing print zork, thingprint '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 01 9 92 50 413 62 124 65 35 139 746 154 15After 6 154 25 count = 0sum = 0print 'Before', count, sumfor value in [9, 41, 12, 3, 74, 15] : count = count + 1 sum = sum + value print count, sum, valueprint '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 $ python search1.py print 'Before'for value in [9, 41, 12, 3, 74, 15] : if value > 20: print 'Large number',valueprint 'After' $ python search1.py BeforeLarge number 41Large number 74After 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 Before FalseFalse 9False 41False 12True 3True 74True 15After True found = Falseprint 'Before', foundfor value in [9, 41, 12, 3, 74, 15] : if value == 3 : found = True print found, valueprint 'After', found If we just want to search and know if a value was found - we use a variable that starts at False and is set to True as soon as we find what we are looking for.

Finding the largest value $ python largest.py Before -19 941 4141 1241 374 7474 15After 74 largest_so_far = -1print 'Before', largest_so_farfor the_num in [9, 41, 12, 3, 74, 15] : if the_num > largest_so_far : largest_so_far = the_num print largest_so_far, the_numprint 'After', largest_so_far We make a variable that contains the largest value we have seen so far. If the current number we are looking at is larger, it is the new largest value we have seen so far.

Finding the smallest value? smallest = -1print 'Before', smallestfor value in [9, 41, 12, 3, 74, 15] : if value < smallest : smallest = value print smallest, valueprint 'After', smallest We make a variable that contains the smallest value we have seen so far. If the current value is smaller, it becomes the new smallest value we have seen so far.

Finding the smallest value smallest_so_far = -1print 'Before', smallest_so_farfor the_num in [9, 41, 12, 3, 74, 15] : if the_num < smallest_so_far : smallest_so_far = the_num print smallest_so_far, the_numprint 'After', smallest_so_far We make a variable that contains the smallest value we have seen so far. If the current number we are looking at is smaller, it is the new smallest value we have seen so far.

What is the Smallest Number? 9 41 12 3 74 15 -1 smallest_so_far

Finding the smallest value $ python largest.py Before -1-1 3-1 41-1 12-1 9-1 74-1 15After -1 smallest_so_far = -1print 'Before', smallest_so_farfor the_num in [3, 41, 12, 9, 74, 15] : if the_num < smallest_so_far : smallest_so_far = the_num print smallest_so_far, the_numprint 'After', smallest_so_far We make a variable that contains the smallest value we have seen so far. If the current number we are looking at is smaller, it is the new smallest value we have seen so far.

Finding the smallest value smallest = Noneprint 'Before'for value in [9, 41, 12, 3, 74, 15] : if smallest is None : smallest = value elif value < smallest : smallest = value print smallest, valueprint 'After', smallest $ python smallest.py Before9 99 419 123 33 743 15After 3 We still have a variable that is the smallest so far. The first time through the loop smallest is None so we take the first value to be the smallest.

The "is" and "is not" Operators 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 smallest = Noneprint 'Before'for value in [3, 41, 12, 9, 74, 15] : if smallest is None : smallest = value elif value < smallest : smallest = value print smallest, valueprint 'After', smallest

Summary While loops (indefinite) Infinite loops Using break Using continue For loops (definite) Iteration variables Counting in loops Summing in loops Averaging in loops Searching in loops Detecting in loops Largest or smallest