Reading: Practical Programming, rest of Chapter 7.
Our first while loop just adds digits and could easily be a for loop
i=1
sum = 0
while i<10:
sum += i
i += 1
print sum
General form of a while loop:
while condition:
block
Steps
In other words, the cycle of evaluating the condition followed by evaluating the block of code continues until the condition evaluates to False.
Here is a while loop to add the non-zero numbers that the user types in.
sum = 0
end_found = False
while not end_found:
x = int( raw_input("Enter an integer to add (0 to end) ==> "))
if x == 0:
end_found = True
else:
sum += x
print sum
We will work through this loop by hand in class.
We can rewrite the above example to terminate the loop immediately upon seeing the 0 using Python’s break:
sum = 0
while True:
x = int( raw_input("Enter an integer to add (0 to end) ==> "))
if x == 0:
break;
sum += x
print sum
break
The while condition of True essentially means that the only way to stop the loop is when the condition that triggers the break is met.
Suppose we want to skip over negative entries in a list. We can do this by telling Python to continue when it sees a blank line:
for item in mylist:
if item < 0:
continue
print item
When it sees continue, Python immediate goes back to the while condition and re-evaluates it, skipping the rest of the loop.
Any while loop that uses break or continue can be rewritten without either of these.
This particular example is probably better without the continue.
One important danger with while loops is that they may not stop!
For example, it is possible that the following code runs “forever”. How?
n = int(raw_input("Enter a positive integer ==> "))
sum = 0
i = 0
while i != n:
sum += i
i += 1
print 'Sum is', sum
How might we find such an error?
We will practice with the Wing IDE debugger in class, using it to understand the behavior of the program. We will explain the following picture
and note the use of
Given two lists L1 and L2 measuring the daily weights (floats) of two rats write a while loop to find the first day that the weight of rat 1 is greater than that of rat 2.
Do either of the following examples cause an infinite loop?
import math
x = float(raw_input("Enter a positive number -> "))
while x > 1:
x = math.sqrt(x)
print x
import math
x = float(raw_input("Enter a positive number -> "))
while x >= 1:
x = math.sqrt(x)
print x
Many numerical simulations, including many video games involve random events.
Python includes a module to generate numbers at random. In particular,
import random
# Print three numbers randomly generated between 0 and 1.
print random.random()
print random.random()
print random.random()
# Print a random integer in the range 0..5
print random.randint(0,5)
print random.randint(0,5)
print random.randint(0,5)
We’d like to use this to simulate a “random walk”:
Many variations on this problem appear in physical simulations.
We can simulate a steps in two ways:
We’ll write the code in class, starting from the following:
import random
# Print the output
def print_platform( iteration, location, width ):
before = location-1
after = width-location
platform = '_'*before + 'X' + '_'*after
print "%4d: %s" %(iteration,platform),
raw_input( ' <enter>') # wait for an <enter> before the next step
#######################################################################
if __name__ == "__main__"
# Get the width of the platform
n = int( raw_input("Input width of the platform ==> ") )
Consider the DNA sequence, represented by the string:
seq = 'ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCC' \
'CCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGC' \
'CTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGG' \
'AAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCC' \
'CTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAG' \
'TTTAATTACAGACCTGAA'
3-letter subsequences encode amino acids. For example, ACA is Threonine, and AGA is Arginine.
As an exercise, ignoring the existence of the find function for strings, write a function that uses a while loop to find and return the index of the first occurrence of a particular amino acid, represented by a three-letter string, in a DNA sequence. It should return -1 if the amino acid is not there. The format of the function is
def find_amino( amino, dna_seq ):
How could you solve the same problem using a for loop and a break, or with no break?
Revise your code so that amino can be an arbitrarily long string instead of just three characters!
Spring break is a good time to go through the concepts we have learnt in this class and make sure you can use them properly in solving problems. Here is a shortlist of some important things we have done since Exam #1.