0% found this document useful (0 votes)
7 views

(PPT) Iteration in Python

while-loop for-loop examples

Uploaded by

createthread
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

(PPT) Iteration in Python

while-loop for-loop examples

Uploaded by

createthread
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Iterative structure in Python

In Python, repetition can be recursive


def count_down_rec(x):
‘’’ Produces the list
[x, x - 1, x - 2, ..., 1,0]
count_down: Nat -> (listof Nat)
‘’’
if x == 0:
return [0]
else:
return [x] + count_down(x-1)
But it can be different  Iteration
def count_down(x):
answer = []
while x >= 0:
answer.append(x)
x=x–1
return answer

What happens when we call count_down(3)?


while loop basics
• If the continuation test is True,
• Execute the loop body
• If the continuation test is False,
• Do not execute the loop body
• After completing the loop body:
• Evaluate the continuation test again
• The body usually includes an update of variables used in the
continuation test
while loop template
## initialize loop variables
while test:
## body, including statements to:
## 1) update variables used in test
## 2) update value being calculated
Steps for writing a while loop
• You must determine
• how to initialize variables outside the loop
• when the loop body should be executed, or, when it should stop
• what variables must be updated in the loop body so the loop will eventually
stop
• what other actions are needed within the loop body
Example: Checking Primality
• A number n >= 2 is prime if it has no factors other than 1 and itself.

• To test if a number n is prime:


• Check every number from 2 to n-1
• If you find a factor of n, stop and return False
• If none of them are, stop and return True
• Determine what steps should be in side the loop, and which should be
outside
Implementation of is_prime
def is_prime (n):
‘’’ is_prime: Nat -> Bool
Requires: n >= 2
‘’’
test_factor = 2
while test_factor < n:
if n % test_factor == 0:
return False
else:
test_factor = test_factor + 1
return True
Beware of “infinite loops”
while True: x = -5
print('runs forever') total = 0
while x < 0:
total += 2.0 ** x
x -= 1
print(total)
Exercise: factorial
• Write a Python function to calculate n!
• Use a while loop that counts from 1 to n
• Use a while loop that counts down from n to 1
Why use loops instead of recursion?
• Iteration may allow for a more “natural” solution
• Python won’t let us do recursion thousands of times
• Iteration is more memory efficient
• for each recursive call, we need memory for parameters
• for an iterative call, we may just need to update an existing variable
• Iteration will generally run faster
Another type of loop: for
• While loops are called guarded iteration:
• If the test evaluates to True, execute the body

• Another approach:
• Iterate over all members in a collection
• Called bounded iteration

for item in collection:


loop_body
for loop examples
for food in ['avocado', 'banana', 'cabbage’]:
print(food.upper())

for base in 'ACGGGTCG’:


print(base)
for loop examples using range
sum_all = 0
for i in range(2, 5):
sq = i * i
sum_all = sum_all + sq
print(sum_all)

for j in range(10, 2, 2):


print(j)

• range is used to generate a collection of integers


• The next value in the range is computed automatically with each pass through the for loop.
for and while

while for
• Loop counter should be • Loop counter initialized
initialized outside loop automatically
• Includes continuation test • Continues while more elements in
before body the collection
• Should update loop variables • Loop variable updated automatically
in body of loop – do not update in loop
• Body contains steps to repeat • Body contains steps to repeat
What does this function do?
def smaller(L, x): • How many iterations would
p=0 smaller([10, 8, 6], 3) involve?
while p < len(L):
if L[p] < x: • smaller([7, 10, 2], 8)?
return p
else: • smaller(L, x) for any L and x?
p = p+1
return False
What does this function do?
def mult_table(n):
table = []
for r in range(n):
row = []
for c in range(n):
row.append(r*c)
table.append(row)
return table

• How many total iterations would mult_table(5) involve?


• mult_table(n) for any Nat n?

You might also like