Professional Documents
Culture Documents
Slides 05 Looping
Slides 05 Looping
Motivation
Looping
While loop
For loops
Mechanics
Conclusion
Writing loops
Working with strings
Loops
Basic algorithms
Michael Burrell
Readings
Chapter 2 — 2.6
Chapter 3 — 3.4, 3.5
Looping
While loop
while condition:
statements
While loop
while condition:
statements
We repeatedly execute the statements in the body of the
loop as long as the condition is true
If the condition is always true, it’s an infinite loop
If the condition is initially false, we do not enter the loop
at all
Mechanics of looping
Example loop
The best way to understand how while loops work is by
tracing through an example.
1 n = int(input(’Enter a number: ’))
2 i = 1
3 while i <= n:
4 print(i)
5 i += 1
Writing loops
Exercises
Let’s write up some Python code which will:
1 Print exponentially increasing numbers
(1, 2, 4, 8, 16, 32, 64, . . . )
2 Determine if a number is a perfect square or not (not
using sqrt)
3 Print every positive integer less than n which is divisible
by 2 or 3
4 Print every other character from a string
5 Reduce a fraction. E.g., 24 60
becomes 25
6 Prints out all integers between an integer n and the
nearest multiple of 10. E.g., 57 will print out 57 58 59
60. E.g., 83 will print out 83 82 81 80
Michael Burrell Loops
Looping
For loops Counting loops
Conclusion
Counting loops
1 for i in range(10):
2 print(i)
Counting loops
Definite loops
Exercises
Let’s write up some Python code which will:
1 Determine whether a number is prime
2 Print out all primes up to 1000
3 Draw a rectangle on the screen using |, - and +
characters
Conclusion
We’ve seen two loops: while and for (only used with
range for now)
These allow us to repeat statements
We will require a lot of practice to get familiar with
common patterns with these