Computer Science 15-110, Fall 2010
Class Notes: Getting Started with while Loops
- The "while" statement
- Examples
- Read Until a Sentinel
- Read Until a Condition
- Find the Nth Positive Integer with Some Property
- Misuse: Iterate Over a Range of Integers
- Practice Tracing
- Practice Mystery Methods
- Practice Problems
Getting Started with while Loops
- The "while" statement
while (test):
body
For example:
def powersOfTwo(upperLimit):
n = 1
while (n < upperLimit):
print n
n *= 2
print "After loop, n = ", n
And a similar example:
def dividingByTwo(n):
count = 0
while (n > 0):
print n
n /= 2
count += 1
print "After loop, n=", n, " and count=", count
And a different example:
def functionsRace(finishLine):
print "Functions race!"
print "Function 1: y1 = 10 * x + 50"
print "Function 2: y2 = x * x - 100"
print "x\ty1\ty2"
x = 0
y1 = 0
y2 = 0
# while loop with conjunct condition
while (y1 < finishLine and y2 < finishLine):
y1 = 10 * x + 50
y2 = x * x - 100
print "%d\t%d\t%d" % (x, y1, y2)
x += 1
if (y1 > y2):
print "Function 1 wins!"
elif (y1 < y2):
print "Function 2 wins!"
else:
print "It's a tie!"
- Examples
- Read Until a Sentinel
# Keep reading names until the user enters "done"
count = 0
sentinel = "done"
input = None
print "Keep entering names. To quit, enter", sentinel
while (input != sentinel):
input = raw_input("Enter name #" + str(count+1) + ": ")
if (input != sentinel):
count += 1
print "You entered", count, "names!"
- Read Until a Condition
# keep reading numbers until their sum exceeds 10
sum = 0.0
while (sum < 10):
print "Sum = " + str(sum) + ". ",
input = float(raw_input("Next number --> "))
sum += input
print "Final sum = ", sum
- Find the Nth Positive Integer with Some Property
# find the nth number that is a multiple of both 4 and 7
def isMultipleOf4Or7(x):
return ((x % 4) == 0) or ((x % 7) == 0)
def nthMultipleOf4Or7(n):
found = 0
guess = -1
while (found <= n):
guess += 1
if (isMultipleOf4Or7(guess)):
found += 1
return guess
input = None
while (input != -1):
input = int(raw_input("Enter a # (or -1 to quit): "))
if (input != -1):
print " nthMultipleOf4Or7(", input, ") =", nthMultipleOf4Or7(input)
print "Bye!"
- Misuse: Iterate Over a Range of Integers
# sum numbers from 1 to 10
# note: this works, but you should not use "while" here.
# instead, do this with "for" (once you know how)
sum = 0
counter = 1
while (counter <= 10):
sum += counter
counter += 1
print "The sum from 1 to 10 is", sum
Once again, but with a bug!:
# sum numbers from 1 to 10
# warning: buggy version!
sum = 0
counter = 0
while (counter <= 10):
counter += 1
sum += counter
print "The sum from 1 to 10 is", sum
And once more, using a "for" loop (which we'll soon learn about):
# sum numbers from 1 to 10
sum = 0
for counter in range(1,11):
sum += counter
print "The sum from 1 to 10 is", sum
- Practice Tracing
- # trace this code by hand, then run it to confirm your prediction
x = 13
y = 1
while (y < x):
print x,y
x -= 2
y += 3
print x,y
- # trace this code by hand, then run it to confirm your prediction
s = "abcde"
while (len(s) < 15):
print s
s += "-" + str(len(s))
print "Done, and s =",s
- Practice Mystery Methods
- # State what this function does, in just a few words of plain English.
# Do not state line-by-line what it does at a low level. Find the general pattern.
# Also note that there is a clearer, faster, better way to do the same thing!
def mysteryA(x, y):
# assume x and y are non-negative integers
c = 0
while (x > 0):
c += y
x -= 1
return c
- # State what this function does, in just a few words of plain English.
# Do not state line-by-line what it does at a low level. Find the general pattern.
# Also note that there is a clearer, faster, better way to do the same thing!
def mysteryB():
c = 0
input = "!" # why do this?
s = ""
while (s.find(str(input)) < 0):
s += str(input)
c += 1
input = "-" + raw_input("Enter an integer: ") + "-"
return c
- Practice Problems
In recitation...
carpe diem -
carpe diem - carpe diem - carpe diem
- carpe diem - carpe diem -
carpe diem - carpe diem - carpe
diem