Loops

When you need to repeat the execution of a few statements multiple times then instead of repeating the statements, you would use a loop construct enclosing statements which need to repeat.

You can use either a while loop or a for loop for such a need.

The while loop

The while statement is used when the program of execution has to repeat a set of statements till a conditional is true:


repeat = True
while repeat:
    user_input = input("Please input anything to continue. " +
                       "If you want to quit, input 'quit' in small case \n")
    print('Your input is "', user_input, '"')
    if user_input == 'quit':
        print("OK have a good day!")
        repeat = False  #  Loop stops here as the conditional becomes False

In this example, you first initialize variable repeat to True. The while construct needs a conditional expression which evaluates to True, similar to if, however in a while, conditional is tested after every iteration. If the conditional expression is True, then the indented block of compound statements after the : (colon) is executed, and is repeated continuously till the conditional becomes False.

In this example, the conditional expression is a variable which has a value of True to begin with. The user is asked to key in any value in every iteration. If the value keyed in by the user is quit then the variable repeat is set to False and the while loop ends at that time. Till then the entire block of statements for the while is repeated.

Points to note

  • The program of execution is in an infinite loop in the above example till the user enters quit. You should always exercise caution with infinite loops as the processor is constantly working on your code without respite and thus using the necessary computing power on your machine till the loop ends.
  • When the program is running a block of code, you see a * on the side bar of Jupyter Notebook.

The for loop

The for statement is another way to create a compound statement block which will be repeated a given number of times. The statements in the for block will be executed in a sequence for a given number of predetermined times.

In Python the for loop can only be used along with a sequence construct. The sequence construct can be any of the type of a range, a list, a tuple, a dictionary, a set, or a string.

Here is an example of a for loop with a range construct for iteration:

for x in range(0, 3):
    # Executes the below statement 3 times, one for each number in the range
    print("This is really fun! Value of x=" + str(x))

Output:
This is really fun! Value of x=0
This is really fun! Value of x=1
This is really fun! Value of x=2

Optional else statement which can be used with both while and for

If you use the optional else statement after compound block, then once the conditional is False in case of while or once the iteration count ends in case of for, the else is executed.

for x in range(3):
    print(x)
else:
    print('Value of x after all the iterations: x = %d' % (x))

Output:
0
1
2
Value of x after all the iterations: x = 2

Iterating Other Constructs

List

The below example shows the use of a for loop iterating a list construct:

scores = [50, 80, 90, 100]
for score in scores:
    print(score)

Output:
50
80
90
100

String

In case of strings you can iterate on each letter

language = 'Python'
for x in language:
    print(x)

Output:
P
y
t
h
o
n

Multidimensional List

Looping over a list of lists

multi_list = [ 
     [1, 2, 3], 
     [4, 5, 6], 
     [7, 8, 9]
     ]
for my_list in multi_list:
    print(my_list)

Output:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

break statement

Any loop, both for and while can be broken off before it completes the required number of iterations of the loop (including loops at any inner level) by using break statement.

multi_list = [ 
     [1, 2, 3], 
     [4, 5], 
     [7, 8, 9]
     ]
for my_list in multi_list:
    print(my_list)
    if len(my_list) == 2:
        break

Output:

[1, 2, 3]
[4, 5]

In the above example, you break the iteration midway with the conditional if statement, before it gets to the third iteration.

continue statement

The continue statement will skip the rest of the statements after the continue statement in the loop block and continues with the next iteration of the loop.

Here is a program to collect all fruits that do not start with 'b':

my_list = []
fruits = ['apple', 'orange', 'banana', 'kiwi', 
          'grapes', 'water melon', 'blue berries', 
          'mandarin', 'grapefruit']
for fruit in fruits:
    if fruit.startswith('b'):
        continue  # If fruit name starts with 'b' continue
    my_list.append(fruit)
print(my_list)

Output:
['apple', 'orange', 'kiwi', 'grapes', 'water melon', 'mandarin', 'grapefruit']

Note that list.append(num) is not invoked when it finds a fruit that starts with 'b' because of continue

enumerate

When it comes to collections, you can use enumerate to get tuples of index and element, from any collection. Here is an example;

my_list = [1, 2, 3, 4]
for i in enumerate(my_list):
    print(i)

output:

(0, 1)
(1, 2)
(2, 3)
(3, 4)

Notice you receive a tuple containing the index and the element from the list. You can replace the above list with a set, tuples, zip etc..

If you want to get index and element separately, you can use enumerate in the below way;

my_set = {('a', 1), ('b', 2), ('c', 3)}

for i, j in enumerate(my_set):
    print(i, j)

output:

0 ('b', 2)
1 ('c', 3)
2 ('a', 1)

In the above, i represents the index number and j represents the individual element. Both are printed in the example.

You can use enumerate to iterate lists, tuples, sets and also zip objects. You will learn about the zip next.

List Comprehension

If you are creating a new list using a for clause with one or more if or for clauses, you could make your code concise by using List Comprehension expression. A list comprehension consists of left and right brackets containing an expression followed by a for clause, and zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.

Here is an example. Suppose you want to multiply all the even numbers upto the given number by 3 and create a new list with the result of this multiplication, you could write a concise program as shown below:


my_list = [num*3 for num in range(1, 10) if num%2 == 0]
print(my_list)

Output:
[6, 12, 18, 24]

Without the list comprehension technique, the same code would have been written as:


my_list = []
for num in range(1, 10):
  if num%2 == 0:
    my_list.append(num*3)
print(my_list)

The only caveat is, you can use this construct only if the expression is not a compound statement. Also the above program can be made more concise by removing the if block completely, as shown below and the above example is given just to show how a list comprehension can be built with an if block.


my_list = []
for num in range(0, 10, 2):
    my_list.append(num*3)
print(my_list)

Reference:https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

results matching ""

    No results matching ""