Python Loops
Python Loops
Samir V
A loop is a code that tells Python to repeat a specified set of actions multiple
times. Often, they iterate over collections of data (such as data held in
dictionaries or lists) .
Imagine you have a list of numbers, and you want to find every number higher
than 10. Without a loop, the code is very long and repetitive.
slide 3
Samir V
for number in my_list:
if number > 10:
print(number)
Eg -
my_list = ["red", "blue", "yellow"]
slide 4
Samir V
For loops with a range() function –
We can use loops with Python’s built-in range() function to state exactly how
many times we want the loop to iterate.
• With just one parameter, the range starts at a default of 0 and finishes at
(not including) the specified number:
slide 5
Samir V
for x in range(3):
print(x)
--Output:
0
1
2
slide 6
Samir V
for x in range(2, 6):
print(x)
-- Output:
2
3
4
5
slide 7
Samir V
for x in range(2, 10, 2):
print(x)
-- Output:
2
4
6
8
slide 8
Samir V
Design for loops to print following sequences-
5
6
7
8
9
0
25
50
75
5
4
3
2
1
Design a for loop that displays numbers from 1-20 that divisible by 3
slide 9
Samir V
Nested for loops -
We can use a loop inside another loop: this is called a nested loop. This is
useful if, for example, you want to loop through a list of lists:.
-- Output:
Kendall is in the group ['Kendall', 'Shiv', 'Roman']
Shiv is in the group ['Kendall', 'Shiv', 'Roman']
Roman is in the group ['Kendall', 'Shiv', 'Roman']
Logan is in the group ['Logan', 'Ewan', 'Gerri']
Ewan is in the group ['Logan', 'Ewan', 'Gerri']
Gerri is in the group ['Logan', 'Ewan', 'Gerri']
Tom is in the group ['Tom', 'Greg']
Greg is in the group ['Tom', 'Greg'] Samir V
slide 10
Create code with a nested loop based on the list of lists
slide 11
Samir V
Break and continue statements in for loops
for wd in words:
if wd == "bingo":
print("The list contains the word bingo")
break
--Output:
The list contains the word bingo
slide 12
Samir V
A continue statement is used to skip the remaining code inside
the loop for the current iteration.
We might want to do this when a certain condition is not met, and
there is no value to continuing the rest of the code for this
iteration.
In the example below we want to find words with first letter “b”
and last letter “o”:
for wd in words:
if wd[0] != "b":
continue
else:
if wd[-1] == "o":
print("The word", wd, "starts with b and ends with o")
-- Output:
The word bingo starts with b and ends with o.
slide 13
Samir V
Create a loop to check whether the list [3, 5, 11, 12, 1] contains at least one
number higher than 10, and prints “This list contains a number higher than 10” if
it does. The output should be as follows:
-- Output
This list contains a number higher than 10
Create a loop to check whether the list of lists [[1, 3, 9], [3, 2], [4, 2] contains any
lists that a) contain exactly two items, and b) the sum of the items is not greater
than 5. The output should be as follows:
-- Output
[3, 2] contains two items which have a sum no greater than 5
slide 14
Samir V
while loop
slide 15
Samir V
The format of a rudimentary while loop is shown below:
while <expr>:
<statement(s)>
The controlling expression, <expr>, typically involves one or more variables that
are initialized prior to starting the loop and then modified somewhere in the loop
body.
slide 16
Samir V
n=5
while n > 0:
n -= 1
print(n)
In this case n is initially 5. The expression in the while statement is n > 0, which is
true, so the loop body executes. Inside the loop body, n is decremented by 1 to 4,
and then printed.
When the body of the loop has finished, program execution returns to the top of
the loop, and the expression is evaluated again. If it is true, loop will execute
again. Its still true, so the body executes again, and 3 is printed.
This continues until n becomes 0. At that point, when the expression is tested, it is
false, and the loop terminates.
Execution would resume at the first statement following the loop body, but there
isn’t one in this case.
Q-
The controlling expression of the while loop is tested first, before anything else
happens. If it’s false to start with, what will happen?
slide 17
Samir V
The break and continue Statements –
slide 18
Samir V
The else Clause
Python allows an optional else clause at the end of a while loop. This is a unique
feature of Python, not found in most other programming languages.
while <expr>:
<statement(s)>
else:
<additional_statement(s)>
If the loop is exited by a break statement, the else clause won’t be executed.
slide 19
Samir V
n=5
while n > 0:
n -= 1
print(n)
if n == 2:
break
else:
print('Loop done.’)
This loop is terminated prematurely with break, so the else clause isn’t executed.
slide 20
Samir V
Infinite Loops –
while True:
print('foo’)
Clearly, True will never be false. Thus, while True: initiates an infinite loop that will
run forever.
slide 21
Samir V