Search Header Logo
Loops (Part 2)

Loops (Part 2)

Assessment

Presentation

•

Science, Computers

•

University

•

Medium

Created by

Vaishnavi Sundararajan

Used 1+ times

FREE Resource

7 Slides • 4 Questions

1

Loops (Part 2)

2

Saw for loops last time

  • Use for when you know how long the loop should last

  • ​for x in range(a, b)

  • for x in {a1, a2, a3, a4}

3

Open Ended

Write a function printn, which takes as input a positive integer n, and prints all the numbers from 0 through n (both inclusive)

4

Indeterminately long loops?

  • What if we don't know how many iterations a loop might have?

  • Example: Write a program nprime that takes as input a positive integer n, and prints the first n prime numbers.

  • Needs us to try indeterminately large sets of numbers, as n grows!​

  • But the terminating condition ("Is the number of prime numbers printed so far less than or equal to n?") is easy to check!​

5

A while loop

def nprime(n) :

.........ct = 0

.........indx = 1​

.........while ​ct < n :

​....................if isprime(indx) :

.................................print(indx)​

.................................ct = ct + 1

....................indx = indx + 1​

6

Another example

  • A while lets us loop on inputs too!

  • Can ask the user for input till the input matches some expected pattern ("Your password must contain an uppercase letter, a lowercase letter, a number, a special character, the blood of your firstborn...")​

7

Multiple Choice

Fill in the blanks so that the following program asks for input till it receives "Ready".

str = ____________

while _________ :

................................................................print("Please enter the exact string 'Ready')

str = input()

1

''

str != 'Ready'

2

'Ready'

str != 'Ready'

3

42

str != 'ready'

4

''

'Ready'

8

Nested loops

  • We saw two types of loops -- for and while

  • We can have nested loops too

  • Often very useful for pretty printing​

  • Write a program which prints the numbers 1 through 20 in four rows, with five elements on each row, separated by tabs

9

Nested for loops

def print1to20() :

.........for i in range(1, 5) :

.................for j in range(1, 5) :

............................print(5*(i-1) + j, end='\t')​

.................print(5*i, end='\n')

​

10

Open Ended

Write a function strspace which takes as input a string and returns the number of spaces in the string

11

Open Ended

Write a function xtable which, given a number n, prints the times table (multiples from 1 through 10) for every number from 1 through n

pattern-tertiary
Loops (Part 2)

Show answer

Auto Play

Slide 1 / 11

SLIDE