Docsity

While loops - Introduction to Computing Using Python - Lecture Slides, Slides of Introduction to Computing

Partial preview of the text

Download While loops - Introduction to Computing Using Python - Lecture Slides and more Slides Introduction to Computing in PDF only on Docsity!

Recall: For Loops

Print contents of seq"

x = seq[0]" print x" x = seq[1]" print x" …" x = seq[len(seq)-1]" print x The for-loop: for x in seq:" print x

• Key Concepts

§ loop sequence: seq § loop variable : x § body : print x § Also called repetend

Iteration: Doing things repeatedly

  1. Process each item in a sequence § Compute aggregate statistics for a dataset,  such as the mean, median, standard deviation, etc. § Send everyone in a Facebook group an appointment time
  2. Perform n trials or get n samples § Draw n cards to make a poker hand § Run a protein-folding simulation for 10 6 time steps
  3. Do something an unknown number of times § CUAUV team, vehicle keeps moving until reached its goal for x in sequence: process x for x in range(n): do next thing ???? Richard King "

While-Loops and Flow

print 'Before while' count = 0 i = 0 while i < 3: print 'Start loop '+i count = count + I i = i + 1 print 'End loop ' print 'After while'

Output:

Before while Start loop 0 End loop Start loop 1 End loop Start loop 2 End loop After while

while Versus for

# process range b..c-

for k in range(b,c)

process k

# process range b..c-

k = b

while k < c:

process k

k = k+

Must remember to increment

# process range b..c

for k in range(b,c+1)

process k

# process range b..c

k = b

while k <= c:

process k

k = k+

Note on Ranges

  • m..n is a range containing n+1-m values § 2 .. 5 contains 2, 3, 4, 5. Contains 5+1 – 2 = 4 values § 2 .. 4 contains 2, 3, 4. Contains 4+1 – 2 = 3 values § 2 .. 3 contains 2, 3. Contains 3+1 – 2 = 2 values § 2 .. 2 contains 2. Contains 2+1 – 2 = 1 values § 2 .. 1 contains ???
  • The notation m..n, always implies that m <= n+ § So you can assume that even if we do not say it § If m = n+1, the range has 0 values

while Versus for

# table of squares to N

seq = []

n = floor(sqrt(N)) + 1

for k in range(n):

seq.append(k*k)

# table of squares to N

seq = []

k = 0

while k*k < N:

seq.append(k*k)

k = k+

Have to know in advance where to stop

Cases to use while

Remove all 3’s from list t

i = 0 while i < len(t):

no 3’s in t[0..i–1]

if t[i] == 3: del t[i] else: i += 1 Sometimes you want to modify the sequence Stopping point keeps changing

Remove all 3’s from list t

while 3 in t: t.remove(3) Maybe this one is easier with no numerical counter

Cases to use while

def sqrt(c): x = c/ while abs(xx – c) > 1e-6: x = x / 2 + c / (2x) return x Sometimes your termination condition has nothing to do with counters