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

Python Basics 02 - Repetitions 2

The document discusses different ways to perform repetitive tasks in Python including for loops, while loops, and list comprehensions. For loops iterate over a sequence, executing a code block for each element. While loops check a logical expression and repeat a code block as long as it remains true. List comprehensions provide a compact way to create new sequences from existing ones using a for loop and optional filter condition.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python Basics 02 - Repetitions 2

The document discusses different ways to perform repetitive tasks in Python including for loops, while loops, and list comprehensions. For loops iterate over a sequence, executing a code block for each element. While loops check a logical expression and repeat a code block as long as it remains true. List comprehensions provide a compact way to create new sequences from existing ones using a for loop and optional filter condition.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Repetitions

One of the most common task when we working on a collection of item is to perform a group
of instructions over each item.
There are three main ways to do this in Python: using a for
loop, a while loop and through list comprehension.
In this video, we will talk about these three ways.
For loop
First, we will discuss the so-called for-loop.
The general syntax for a for-loop block is as follows:
for looping_variable in sequence:

code block

The looping variable is assigned to the first element of the sequence and the code block is
executed.
After the execution, the second element of the sequence is assigned to the
looping variable and again, the code block is executed. This repeats until there are no more
elements in the sequence to assign to the looping variable.
Let's have an example:
In [1]:
word = "banana"

for letter in word:

print(letter)

In the above example, the looping variable is named letter and the sequence is the string
"banana" .
In the code block, we are simply printing the value of the looping variable
letter at each repetition.

What is important to note in the structure above is the use of colon at the end of the line
starting at for , and also that the code block that is executed every repetition must be
indented. If there are multiple codes in the block, all the codes must have the same indent.
Other examples of sequences that we can iterate over include elements of a list, a tuple and
other sequential data types. Given below are some more examples to help us better
appreciate the power of for-loops.
In [2]:
for n in range(5):

print(n)

For the example above, notice that there is a new command introduced, that is, range(5) .
This essentially generates a sequence of numbers that begin at 0 and end at 4.
On the first iteration, the looping variable n has a value of 0 . Since the code block
asks n to be printed, the first line of the output is 0 .
On the second iteration, the looping variable n has a value of 1 . From the code block,
the looping variable gets printed, therefore, the second line of the output is 1 .
and so on until the last element of the sequence, which is 4 , is printed.
The command range , in its simple form, has the syntax range(start,stop,step) . As
in index for splicing, step is optional with 1 as default and the resulting sequence does not
include the value of stop .
In [3]:
word = "banana"

for i in range(len(word)):

n=i+1

print(n, word[:n])

1 b

2 ba

3 ban
4 bana

5 banan

6 banana

The code above displays the different prefix of the word "banana" , starting from prefix of
length 1, length 2 up to length 6. Here, we use the length of the variable word as input to
the range command.
Also,we use string splicing to get the prefixes.
The example above also shows a code block having multiple lines. What is important to note
is that all the lines have the same indent. This is Python's way to recognize the group of lines
associated with the code block for the for-loop.
Our final example is the code below. This shows a common way by which items in a
dictionary is accessed using the for-loop. We essentially used the method items() of a
dictionary to access each key-value pair. It is also worth noting that here, we are using two
looping variables, i.e. key and value. The code block simply prints a key-value pair each
iteration.
In [4]:
dict1 = {"one":1, "two":2, "three":3}

for key,value in dict1.items():

print(key, value)

one 1
two 2
three 3

While Loop
Another technique for repetition io use a while loop.
The syntax of a while loop is as follows:
while logical expression:

code block
One of the crucial component of a while loop is its associated logical expression.
A logical
expression evaluates to either a True or False . An example of logical expressions are
comparisons.
In a while loop, Python first checks if the logical expression is true.
If yes, then the code
block is executed.
Once code block is executed, Python goes back to the logical expression
to check if it remains true.
If yes, the code block is repeated and goes back to check
whether the logical expression still holds.
This goes on until the logical expression eventually
becomes false. In this case, the while loop terminates.
In [5]:
n = 0

while n<5:

print(n)

n=n+1

In the example above, the logical expression is n<5 and the code block is given in lines 3
and 4.
In line 3, the instruction is to print the current value of variable n while in line 4, the
value of n is updated by adding 1 to its current value.
Initially, the value of n is 0 , thus, the first check of the expression evaluates to true. In the
first execution of lines 3 and 4, zero is printed, and then the value of n becomes 1 .
The logical expression is again evaluated, this time the value of n is 1.
Since 1 is still less
than 5, lines 3 and 4 will again be executed: the number 1 is printed and then the variable n
is incremented by 1. Thus, the variable n becomes 2, and so on, until the variable n
eventually reaches the value 5 .
In this case, upon checking the value of n<5 , since 5 is not less than 5, the logical
expression becomes false and the while loop terminates.
Notice that the code above has the same effect as the ff. for-loop we discussed earlier.
In [6]:
for n in range(5):

print(n)

In general, a for loop can be rewritten using a while loop but not the other way around.
The while loop is more flexible because it can allow for unbounded number of iterations.
However, while loop can result to an infinite loop when the truth of the logical expression
is unchanged by the code block.
In [7]:
n = 0

while n > -1:

n += 1

---------------------------------------------------------------------------

KeyboardInterrupt Traceback (most recent call last)

<ipython-input-7-4b2e0322348c> in <module>

1 n = 0

2 while n > -1:

----> 3 n += 1

KeyboardInterrupt:
The code above is an example of an infinite loop. The logical expression n > -1 will never
be false because the starting value of variable n is zero and the code block only increments
its value. Thus, n will never be -1.
We can terminate the infinite loop manually by pressing the black square button in the menu,
indicating kernel interruption .
List comprehension
Comprehension is a convenient way Python allows creation of sequence from other
sequence using a very compact syntax.
The general syntax of a simple list comprehension is composed of two parts:
[output input_sequence]

Let's look at an example:


In [11]:
nums = [0,1,2,3,4]

nums_squared = [n**2 for n in nums]

nums_squared

Out[11]: [0, 1, 4, 9, 16]

The original sequence is nums and the created sequence is assigned to the
nums_squared . Notice that the list comprehension at line 2 is essential a for-loop
enclosed in square brackets.
The instruction inside is saying that we get the square of for
each element in the list nums .
Te new list nums_squared is generated from this squares
of numbers.
Also note that the order of the numbers in nums is preserved in the ordering for
nums_squared so 0 is 0^2, 1 is 1^2, 4 is 2^2, 9 is 3^2 and 16 is 4^2.

A list comprehension can only be composed of three parts:


[output input_sequence
condition]

Given below is an example:


In [15]:
nums_squared_even = [n**2 for n in nums if n%2==0]

nums_squared_even

Out[15]: [0, 4, 16]

The only diffence between the list comprehension for nums_squared and
nums_squared_even is the presence of the if part.

The if part represents the condition that should be satisfied in order to be included in the
created list.
The instruction in the comprehension is saying "square the number for each number in the
list nums provided the remainder when dividing the number by two is zero." So this
condition will only be satisfied by even numbers.
Since 1 and 3 in nums are not even, they are not processed in the creation of the new list.
As a result, 1 and 9 are not in the created list.
Summary
Let's now recap what we have learned so far. We essentially learned the different ways to
perform repetitions. We learned of three ways to do this: through a for loop, a while
loop and through list comprehension.

You might also like