Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Slides:



Advertisements
Similar presentations
While loops.
Advertisements

Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Introduction to Computing Science and Programming I
Computer Science 1620 Loops.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Loops and Iteration Chapter 5 Python for Informatics: Exploring Information
Fundamentals of Python: From First Programs Through Data Structures
4. Python - Basic Operators
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Fundamentals of Python: First Programs
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Q and A for Section 4.4 CS 106, Fall Q1 Q: The syntax for an if statement (or conditional statement) is: if _______________ : _____________ A: if.
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.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
Chapter 2 - Algorithms and Design
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
If statements while loop for loop
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
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.
Q and A for Chapter 7 Students of CS104, and me, your benevolent professor, Victor T. Norman, PhD.
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.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping with.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
CS101 Computer Programming I Chapter 4 Extra Examples.
Topic 14 while loops and loop patterns Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Xiaojuan Cai Computational Thinking 1 Lecture 8 Loop Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
Structured Programming The Basics. Control structures They control the order of execution What order statements will be done in, or whether they will.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Loop Invariants and Binary Search Chapter 4.4, 5.1.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Algorithms and Pseudocode
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops.
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
General Condition Loop A general condition loop just loops while some condition remains true. Note that the body of the loop should (eventually) change.
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
PH2150 Scientific Computing Skills Control Structures in Python In general, statements are executed sequentially, top to bottom. There are many instances.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Q and A for Section 4.4 CS 106, Fall If statement syntax Q: The syntax for an if statement (or conditional statement) is: if _______________ : _____________.
More about Iteration Victor Norman CS104. Reading Quiz.
Introduction To Repetition The for loop
Repetition (While-Loop) version]
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.
Python - Loops and Iteration
Computer Science 101 While Statement.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Outline Altering flow of control Boolean expressions
Topic 14 while loops and loop patterns
Coding Concepts (Basics)
Introduction to Problem Solving and Control Statements
CHAPTER 6: Control Flow Tools (for and while loops)
Another Example Problem
CS Problem Solving and Object Oriented Programming Spring 2019
Presentation transcript:

Q and A for Section 5.1 CS 106, Fall 2014

While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while : or, condition

Difference from for loop Q: How often does a while loop execute its ? A: until the boolean condition is False. Note: that’s how it differs from for loop.

while loop vs. for loop Q: When would you use a while loop instead of a for loop? A: When you don't know how many times you need to run the body of the loop. For loop is definite iteration; while loop is indefinite iteration.

Changing the condition Q: Suppose you have a while loop like this: while var1 var2: Is it good/bad/ugly to alter the value of var1 or var2 in the body of the loop? A: You almost *always* alter the value of var1 or var2 in the body, or you would have an infinite loop.

while loop vs. index-based for loop for i in range(len(data)): use data[i] in body i = 0 while i < len(data): use data[i] in body i = i + 1

Infinite loop? Q: When would a while loop run forever (i.e., when would it be an infinite loop)? A: When the boolean expression is always True.

Newton’s Method getSqrtOf = float(raw_input(“Enter a number: “)) # Set oldEst and newEst to any initial values oldEst = 1.0 newEst = 4.0 # while last 2 estimates are quite different while abs(newEst - oldEst) > : # store previous estimate in oldEst oldEst = newEst # compute a new estimate and print it newEst = (oldEst + getSqrtOf / oldEst) / 2.0

Q: Thwarting an infinite loop Q: How would we make sure the following code does not run forever (without changing do_stuff() or update_x())? while some_cond(x): do_stuff() x = update_x(x)

A: Thwarting an infinite loop num_runs = 0 while some_cond(x) and num_runs < 10000: do_stuff() x = update_x(x) num_runs += 1

Checking for item in list (p 162) Q. What is bad about this loop (where you search for item val in list data )? found = False for item in data: if item == val: found = True A. Continues searching even after the item is found.

Checking for item in list (p 162) Q. What is bad about this loop (where you search for item val in list data )? for item in data: if item == val: found = True else: found = False A. It is wrong! If you find an item but there are more items, you “reset” found to False.

Checking for item in list (p 162) Q. Why have i < len(data) in this code? i = 0 found = False while i < len(data) and not found: if data[i] == val: found = True else: i = i + 1 A. This is index-based search. You have to make sure i does not “go off” the end of the list, if val is not in the list.

While loops and user input Q: What is bad about this code? guests = [] name = raw_input(“Enter a name (blank to end): “) while name != “”: guests.append(name) name = raw_input(“Enter a name (blank to end): “) print “You entered”, len(guests), “guests.” A: The line name = raw_input… has to be written twice…

While loops and user input (2) Q: What is bad about this fix? guests = [] name = ‘fake’ while name != “”: name = raw_input(“Enter a name (blank to end): “) if name != “”: guests.append(name) print “You entered”, len(guests), “guests.” A: We are now testing the “stop condition” twice!

While loops and user input (3) Q: What is wrong with this fix? guests = [] name = ‘fake’ while name != “”: name = raw_input(“Enter a name (blank to end): “) guests.append(name) print “You entered”, len(guests), “guests.” A: We are now inserting the empty string at the end of the guests list. Fix by adding guests.pop() before the print statement.

While loops and user input (4) Best solution: use break (duh!) guests = [] while True: name = raw_input(“Enter a name (blank to end): “) if name == “”: break guests.append(name) print “You entered”, len(guests), “guests.” Using break in this manner allows you to do a “mid- loop” test. Otherwise, we can only do “pre-loop” test.

Rewrite this code number = 0 while not 1 <= number <= 10: number = int(raw_input(“Enter a single digit: “)) if not 1 <= number <= 10: print ‘Your number is not a single digit.’

Rewrite this code: Answer while True: number = int(raw_input(“Enter a single digit: “)) if 1 <= number <= 10: break else: print ‘Your number is not a single digit.’

What is wrong with this code? while i < j: # or a for statement someCode() someMoreCode() if some_condition(): break continue A: Don’t need continue at the end of a loop body – it will go back to the top anyway!

Efficiency Q: Are there instances where while loops are always more efficient than if statements? Which is more efficient: while loops or for loops? A: while and if are different (although syntactically very similar). while is a loop; if is a single test. for and while have generally the same efficiency.

Why don’t the authors like break/continue? A: The authors are, perhaps, purists. It *is* nice to be able to look at a loop and know that you enter it from the top, and exit it when the loop is all done ( for ) or the condition is False ( while ). If you have break in the middle, you create another “exit point”. There is a branch of CS where you try to prove that code is correct, with pre-conditions, mid-conditions, post-conditions, etc. That goes out the door with break.

Old Slides

continue statement Used only within a loop body – in loop body itself, or within a body within the loop body. – for while loops and for loops. Makes control go back to the top of the loop. Often used when code detects that nothing else needs to be done with the current element of the loop.

One use of continue : to filter # Plot each earthquake, skipping comment lines # and the header line. for line in input_lines: fields = line.split() if len(fields) == 0: # skip blank line continue if fields[0].startsWith("#"): # skip comment lines continue if fields[0] == 'Src': continue # do stuff with fields.

break statement also used only in loop body -- for loop or while loop. causes control to pass to first line after end of loop body. – i.e., you "break" out of the loop. useful for when searching through a sequence until you find what you are looking for. allows you to make a “mid-loop test”.

Mid-loop test while statement is pre-loop test Other languages have post-loop test: repeat: do_stuff() until Using while True and break, you can do mid-loop test. (Useful for getting user input.) while True: do_stuff() if : break do_other_stuff()

Example of use of break # find if num is a prime isPrime = True # assume it is prime for div in range(2, num / 2 + 1): if num % div == 0: # divides with no remainder # found a divisor so num is not prime isPrime = False break # isPrime is True mean num is a prime number.

Example of use of break # looking for first room with someone in it. found = False for room in rooms: if not room.is_empty(): found = True break if found: room.invite_to_dance_the_night_away()

Practice while loops Problem: Convert the following into an index- based loop: for g in groceries: print g Answer: for i in range(len(groceries)): print groceries[i]

Practice while loops Problem: Convert the following into a while loop: for g in groceries: print g Answer: i = 0 while i < len(groceries): print groceries[i] i += 1

More practice: robots and obstacles Problem: Given a function seeObstacle() that returns True when an obstacle is in front of a robot, write an algorithm to have the robot detect and print out distance to the 8 obstacles around it at N, NE, E, SE, S, SW, W, NW.

More practice: robots and obstacles Solution: for dir in range(8): # 8 directions dist = 0 while not seeObstacle(): goForward(5) # cm. dist += 5 print “distance is”, dist goBackward(dist) turnRight(45) # degrees

Average of numbers Problem: write code to prompt the user for a number, until the user enters “q”. When the user enters “q”, print the average of the numbers that were entered.

Average of numbers total = 0 numNums = 0 while True: num = raw_input(“Enter a number, q=quit:”) if num == “q”: break total += float(num) numNums += 1 if numNums == 0: print “No numbers entered” else: print “Average is “, float(total) / numNums