Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Loops

The document provides an overview of loops in Python, including for loops and while loops, explaining their syntax and use cases. It covers the functionality of range(), nested loops, as well as break and continue statements. Additionally, it introduces the unique else clause for while loops and discusses infinite loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Loops

The document provides an overview of loops in Python, including for loops and while loops, explaining their syntax and use cases. It covers the functionality of range(), nested loops, as well as break and continue statements. Additionally, it introduces the unique else clause for while loops and discusses infinite loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Loops in Python

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) .

Why are loops useful?


In Python, a for loop can be used in two ways. It can either repeat a block of
code a pre-defined number of times, or it can cycle each item in a list.

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.

my_list = [3, 10.1, 62, 9]

if my_list[0] > 10: print(my_list[0])


if my_list[1] > 10: print(my_list[1])
if my_list[2] > 10: print(my_list[2])
if my_list[3] > 10: print(my_list[3])
slide 2
Samir V
For loop

slide 3
Samir V
for number in my_list:
if number > 10:
print(number)

The syntax for a for loop is as follows:

for variable in < iterable-object > :


statement(s)

Eg -
my_list = ["red", "blue", "yellow"]

for color in my_list:


print(color)

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.

This function can be used in a following ways:

• With just one parameter, the range starts at a default of 0 and finishes at
(not including) the specified number:

• With two parameters, we set the start and finish numbers


of the range:

• With three parameters, we set the start and finish


numbers of the range, and the step value (the interval
between each iteration):

slide 5
Samir V
for x in range(3):
print(x)

--Output:
0
1
2

The range starts with 0 and will go up to 3 but doesn't


include 3 .

slide 6
Samir V
for x in range(2, 6):
print(x)

-- Output:
2
3
4
5

The range starts with 2 and will go up to 6 but doesn't


include 6 .

slide 7
Samir V
for x in range(2, 10, 2):
print(x)

-- Output:
2
4
6
8

The range starts with 2 and will go up to 10.


Every time it processes a number. The next number is
calculated by adding step value highlighted in yellow.

We can have loop to count reversed way as well.

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:.

groups = [["Kendall", "Shiv", "Roman"], ["Logan", "Ewan", "Gerri"], ["Tom",


"Greg"]]

# this first loop iterates through groups:


for grp in groups:
# this second loop iterates through the people in each group:
for person in grp:
print(person, "is in the group", grp)

-- 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

[["go", "went", "gone"], ["see", "saw", "seen"], ["take", "took", "taken"]


that produces the following output:

The conjugations of go are:


go
went
gone
The conjugations of see are:
see
saw
seen
The conjugations of take are:
take
took
taken

slide 11
Samir V
Break and continue statements in for loops

A break statement can be used to exit a loop before all the


iterations have finished. We might want to do this when a
certain condition is met, and there is no value to continuing
to loop.

In the example below, we want to check whether a list


contains the word “bingo”:

words = ["tennis", "poker", "bingo", "chess"]

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”:

words = ["tennis", "poker", "bingo", "chess"]

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.

When a while loop is encountered, <expr> is first evaluated. If it is true(i.e.


condition is satisfied), the loop body is executed. Then <expr> is checked again,
and if still true, the body is executed again. This continues until <expr> becomes
false, at which point loop execution stops and program execution proceeds to the
next statement outside 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 –

They behave same as in for loop.

The Python break statement immediately terminates a loop entirely. Program


execution proceeds to the first statement following the loop body.

The Python continue statement immediately terminates the current loop


iteration. Execution jumps to the top of the loop, and the controlling expression is
re-evaluated to determine whether the loop will execute again or terminate.

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.

The syntax is shown below:

while <expr>:
<statement(s)>
else:
<additional_statement(s)>

When <additional_statement(s)> are placed in an else clause, will be executed


only if the loop terminates “by exhaustion”—that is, if the loop iterates until the
controlling condition becomes false.

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

You might also like