More Looping Structures

Slides:



Advertisements
Similar presentations
Execution Control Structures
Advertisements

COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Chapter 4: Looping CSCI-UA 0002 – Introduction to Computer Programming Mr. Joel Kemp.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Programming for Linguists An Introduction to Python 24/11/2011.
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.
Programming for Engineers in Python Sawa 2015 Lecture 2: Lists and Loops 1.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1 >>> while b < 10:... print b... a, b = b, a+b WHILE.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Flow of Control Part 1: Selection
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Chapter 4: Control Structures II
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
1 Chapter 9. To familiarize you with  Simple PERFORM  How PERFORM statements are used for iteration  Options available with PERFORM 2.
CS 100 Introduction to Computing Seminar October 7, 2015.
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 5 Repetition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
Tutorial 9 Iteration. Reminder Assignment 8 is due Wednesday.
Introduction to Computing Using Python Execution Control Structures  Conditional Structures  Iteration Patterns, Part I  Two-Dimensional Lists  while.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Control Structures WHILE Statement Looping. S E Q C E N U E REPITITION …a step or sequence of steps that are repeated until some condition is satisfied.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
PH2150 Scientific Computing Skills Control Structures in Python In general, statements are executed sequentially, top to bottom. There are many instances.
More about Iteration Victor Norman CS104. Reading Quiz.
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
Chapter 6: Loops.
REPETITION CONTROL STRUCTURE
Chapter 3: Decisions and Loops
Python: Control Structures
CS1010 Programming Methodology
Ch 7: JavaScript Control Statements I.
Topics Introduction to Repetition Structures
Outline Altering flow of control Boolean expressions
Iteration: Beyond the Basic PERFORM
Iteration: Beyond the Basic PERFORM
More Looping Structures
Topics Introduction to Repetition Structures
Repetition Control Structure
CMSC201 Computer Science I for Majors Lecture 09 – While Loops
Introduction to Repetition Structures
A LESSON IN LOOPING What is a loop?
CHAPTER 6: Control Flow Tools (for and while loops)
Topics Introduction to Repetition Structures
More Looping Structures
REPETITION Why Repetition?
LOOP Basics.
Presentation transcript:

More Looping Structures Introduction to Computing Using Python More Looping Structures while loop continue – restart a loop break – discontinue a loop

Why do we need a while loop? Introduction to Computing Using Python Why do we need a while loop? We have a for loop that does these things very well: iterate over each element of a sequence for elem in sequence: # do some stuff loop a fixed number of times for i in range(num): # do some stuff So why do we need another loop?

A for loop may not work well because Introduction to Computing Using Python A for loop may not work well because The repetition may not be based on a iterable or sequential object We don't always know how many times to loop in advance so for i in range(num): doesn't work Sometimes we need to refer to elements of a sequence that we have already iterated past or have not yet gotten to so looping over elements one at a time isn't a natural way to repeat

A while loop lets you specify any controlling condition that you want Introduction to Computing Using Python A while loop lets you specify any controlling condition that you want while <condition>: <indented code block> <non-indented statement> condition True <indented code block> False <non-indented statement>

Introduction to Computing Using Python while loop Example: compute the smallest multiple of 7 greater than 37. i = 7 Idea: generate multiples of 7 until we get a number greater than 37 i <= 37 ? i <= 37 ? >>> i = 7 >>> while i <= 37:         i += 7    >>> i 42 >>> i = 7 >>> while i <= 37:         i += 7    >>> i 42 >>> i = 7 >>> while i <= 37:         i += 7    >>> i = 7 >>> True True i += 7 i += 7 False False i

Exercise Write function getNegativeNumber() that uses a while loop to: Introduction to Computing Using Python Write function getNegativeNumber() that uses a while loop to: prompt a user for input as many times as necessary to get a negative number return the negative number Should the return statement be inside the while loop or after it? Why?

Sequence loop pattern 1 1 2 3 5 8 13 21 34 55 + + + + + + + + + Introduction to Computing Using Python Generating a sequence that reaches the desired solution Fibonacci sequence 1 1 2 3 5 8 13 21 34 55 . . . + + + + + + + + + Find the first Fibonnaci number greater than some bound def fibonacci(bound): '''loop through the Fibonacci numbers while the current Fibonacci number is less than or equal to bound, then return the smallest Fibonacci number greater than bound''' # initialize the previous and current Fibonacci numbers previous = current = 1 while current <= bound: # update the values of previous and current previous, current = current, previous+current return current

Infinite loop pattern An infinite loop provides a continuous service Introduction to Computing Using Python An infinite loop provides a continuous service >>> hello2() What is your name? Sam Hello Sam What is your name? Tim Hello Tim What is your name? >>> hello2() What is your name? Sam Hello Sam What is your name? Tim Hello Tim What is your name? Alex Hello Alex What is your name? >>> hello2() What is your name? >>> hello2() What is your name? Sam Hello Sam What is your name? This is an example of a greeting service. The server could be a time server, or a web server, or a mail server, or… def hello2(): '''a greeting service that repeatedly request the name of the user and then greets the user''' while True: name = input('What is your name? ') print('Hello {}'.format(name))

Using a 'flag' to terminate a loop Introduction to Computing Using Python Using a 'flag' to terminate a loop Example: a function that creates a list of cities entered by the user and returns it The empty string is a “flag” that indicates the end of the input def cities(): rtnlst = [] while True: city = input('Enter city: ') # if user enters empty string if city == '': # then return lst return lst # else append city to lst lst.append(city) >>> cities() Enter city: Lisbon Enter city: San Francisco Enter city: Hong Kong Enter city: ['Lisbon', 'San Francisco', 'Hong Kong'] >>>

The continue statement Introduction to Computing Using Python The continue statement: is used inside the body of a for or while loop interrupts the current iteration of the loop transfers execution to the top of the loop def getAges(letter): ''' Get the age of every person whose name begins with letter''' rtnLst = [] while True: name = input('Enter name: ') if name == '': return rtnLst if name[0] != letter: continue age = input('Enter age: ') rtnLst.append(age)

The break statement The break statement: Introduction to Computing Using Python The break statement: is used inside the body of a for or while loop terminates execution of the loop execution transfers to the statement that follows the loop body. while True: city = input('Enter city: ') if city == '': return lst lst.append(city) def cities2(): lst = [] while True: city = input('Enter city: ') if city == '': break lst.append(city) return lst

break / continue in nested loops Introduction to Computing Using Python The continue/break statements: are used inside the body of a for or while loop when executed, they alter the flow of execution In both cases, if the current loop is nested inside another loop, only the innermost loop is affected def before0(table): for row in table: for num in row: if num == 0: break print(num, end=' ') print() def ignore0(table): for row in table: for num in row: if num == 0: continue print(num, end=' ') print() >>> table = [ [2, 3, 0, 6], [0, 3, 4, 5], [4, 5, 6, 0]] >>> before0(table) 2 3 4 5 6 >>> ignore0(table) 2 3 6 3 4 5 4 5 6