More Looping Structures

Slides:



Advertisements
Similar presentations
Execution Control Structures
Advertisements

Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
More Looping Structures
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
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.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
CS 100 Introduction to Computing Seminar October 7, 2015.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Introduction to Computing Using Python Execution Control Structures  Conditional Structures  Iteration Patterns, Part I  Two-Dimensional Lists  while.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
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.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
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.
Chapter 2 Writing Simple Programs
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
Control Flow (Python) Dr. José M. Reyes Álamo.
Fundamentals of PL/SQL part 2 (Basics)
Chapter 6: Loops.
REPETITION CONTROL STRUCTURE
Chapter 3: Decisions and Loops
Repetition (While-Loop) version]
The switch Statement, and Introduction to Looping
CS161 Introduction to Computer Science
Topics Introduction to Repetition Structures
Python: Control Structures
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.
Chapter 5: Control Structures II
ITM 352 Flow-Control: if and switch
CS1010 Programming Methodology
Repetition-Counter control Loop
Ch 7: JavaScript Control Statements I.
Chapter 6: Conditional Statements and Loops
Topics Introduction to Repetition Structures
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
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.
Looping.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 13 (Reed) - Conditional.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Outline Altering flow of control Boolean expressions
Additional Control Structures
Iteration: Beyond the Basic PERFORM
Iteration: Beyond the Basic PERFORM
Topic 1: Problem Solving
Loops CIS 40 – Introduction to Programming in Python
Topics Introduction to Repetition Structures
Repetition Control Structure
CMSC201 Computer Science I for Majors Lecture 09 – While Loops
Computing Fundamentals
Introduction to Repetition Structures
Alternate Version of STARTING OUT WITH C++ 4th Edition
A LESSON IN LOOPING What is a loop?
CHAPTER 6: Control Flow Tools (for and while loops)
Topics Introduction to Repetition Structures
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
More Looping Structures
Chapter 13 Conditional Repetition
A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 13 (Reed) - Conditional.
REPETITION Why Repetition?
LOOP Basics.
Flow Control I Branching and Looping.
Presentation transcript:

More Looping Structures Introduction to Computing Using Python More Looping Structures while loop continue – restart loop from the top break – jump out of 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> while condition True <indented while block> start False <statement following the while loop>

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 True True 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 Fibonacci 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, 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 This is an example of a greeting service. The server could be a time server, or a web server, or a mail server, or … >>> hello() 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? def hello(): '''provide a greeting service that repeatedly requests a user name 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 >>> cities() Enter city: Lisbon Enter city: San Francisco Enter city: Hong Kong Enter city: ['Lisbon', 'San Francisco', 'Hong Kong'] >>> def cities(): rtnlst = [] while True: city = input('Enter city: ') # if user enters empty string if city == '': return lst # else append city to lst lst.append(city)

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 (for or while line) 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 transfers execution to the statement that follows the loop 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 For both continue and break, if the current loop is nested inside another loop, only the innermost loop is affected def before(table): for row in table: for num in row: if num == 0: break print(num, end=' ') print() def ignore(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]] >>> before(table) 2 3 4 5 6 >>> ignore(table) 2 3 6 3 4 5 4 5 6