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 ")
    print(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 : 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

  • Although it is recommended to always indent the block of code for a conditional, sometimes you will see code in which all statements are in one line, separated by a semicolon ; The different variations that are all possible are shown below for the if block in the previous example:
  • If you use semicolor at the end of every statement it does not hurt but in Python it is not required.
  • 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.
if (user_input == 'quit'): print("OK have a good day!"); repeat = False
if (user_input == 'quit'): 
   print("OK have a good day!"); repeat = False

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

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 list in multi_list:
    print(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 list in multi_list:
    print(list)
    if len(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 even numbers from 1 to 10 (excluding 10)in a list and print it in the end and print all odd numbers as they are found:

list=[]
for num in range(1, 10):
    if num % 2:
        print("Found odd number", num)
        continue  # If odd number continue
    list.append(num)
print(list)

Output:

Found an odd number 1
Found an odd number 3
Found an odd number 5
Found an odd number 7
Found an odd number 9
[2, 4, 6, 8]

Note that list.append(num) is not invoked when it finds an odd number 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;

list = [1, 2, 3, 4]
for i in enumerate(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;

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

for i, j in enumerate(myset):
    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 multiple all the even numbers upto the given number by 3 and create a new list of the result of this multiplication, you could write a concise program as shown below:


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

Output:
[6, 12, 18, 24]

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


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

The only caveat is, you can use this construct only if the expression is not a compound statement.

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

results matching ""

    No results matching ""