LOOP STATEMENT


Most of the time, we encounter a situation in which we need to execute a statement or set of statements multiple times. Such repetitive tasks can be achieved using loop statements. Python programming supports : for-loop and while-loop.

The range() function: 

Before we learn about the looping statement, let's learn about the most commonly used range() function in python. The range() function is used to sequence sequence of number, its general form is:

range(start, stop[, step]) -> range object
 |  
 |  Return an object that produces a sequence of integers from start (inclusive)
 |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 |  These are exactly the valid indices for a list of 4 elements.
 |  When step is given, it specifies the increment (or decrement).

Examples:

range(0,10)

Output:

range(0, 10)

by default, range function returns range object, it can be typecast into list object as:

list(range(0,10))

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# or simply
list(range(10))

#range(start,stop,step)
list(range(5,20,4))

list(range(-10,10,2))

range() function is most commonly used with for-loop to iterate over sequences.

for-loop 

Unlike other programming languages, The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. The general form of for-loop is:

for item in iterable:
    # Code block to be executed for each item
    # ...


- item is a variable that takes on the value of each element in the iterable object during each iteration of the loop.
- iterable is any Python object capable of returning its members one at a time, such as a list, tuple, string, range, or any custom iterable object.
- The colon (:) indicates the beginning of the indented block of code that will be executed for each iteration.
- The indented block of code is the body of the loop, where you put the code that you want to execute for each item in the iterable.

Working of for-loop:

# Example: Using a for loop to iterate over a list of numbers and print each number.
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)

Explanation:

  • In this example, we have a list of numbers [1, 2, 3, 4, 5].
  • The for loop iterates over each element in the list numbers.
  • For each iteration, the variable num takes on the value of the current element in the list.
  • Inside the loop, we print the value of num.
  • The loop continues until all elements in the list have been processed.

Other Examples:

words = ['apple','ball','cat','dog']
for word in words:
  print(f'{word}: {len(word)}')

Iterate over string objects as follows:

# to iterate over string
a = "kathmandu"
# let us first generate the index sequence for the string
list(range(len(a))) # output: [0, 1, 2, 3, 4, 5, 6, 7, 8]

Now we can access the index of string as follows:

for i in range(len(a)):
  print(i)

# now we can access the string using its index as follows:
for i in range(len(a)):
  print(a[i])

Now we can do same for list objects:

for i in list(range(-10,10,2)):
  print(i)

Output:


-10
-8
-6
-4
-2
0
2
4
6
8

To iterate over dictionaries we can use its built-in method: .items() => which generates a list of tuples as: [(k,v),(k,v) , ….]

k = {'a':10,'b':20,'c':30,'d':40,'e':50}
k.items() # it generates list of tuples as: dict_items([('a', 10), ('b', 20), ('c', 30), ('d', 40), ('e', 50)]) 

# now list can easily be iterated as:
for key,value in k.items():
  print(key,value)

 while-loop in python

In Python, the while loop is used to repeatedly execute a block of code as long as a specified condition is true. It continues looping as long as the condition remains true, and stops when the condition becomes false. The general form of while loop is:

initialize loop counter
while condition:
    # Code block to be executed while condition is true
    # ...
    # update loop counter
  • condition is the expression that is evaluated before each iteration of the loop. If the condition evaluates to True, the loop continues; if it evaluates to False, the loop terminates.
  • The colon (:) indicates the beginning of the indented block of code that will be executed repeatedly as long as the condition remains true.
  • The indented block of code is the body of the loop, where you put the code that you want to execute repeatedly.

python code: To print numbers from 5 to 1

# Example: Using a while loop to count down from 5 to 1 and print each number.
count = 5

while count > 0:
    print(count)
    count -= 1

 break Statement:

The break statement is used to exit the loop prematurely. It terminates the current loop and transfers the execution to the statement immediately following the loop. Syntax of break statement:

while condition:
    # Code block
    if condition_to_break:
        break
    # More code
# Example: Using a while loop with break statement to exit the loop when a condition is met.
count = 1

while True:
    print(count)
    count += 1
    if count > 5:
        break

# The loop terminates when the value count >5

continue Statement:

The continue statement is used to skip the remaining code inside the loop for the current iteration and proceed to the next iteration. It does not terminate the loop; instead, it skips the rest of the code block for the current iteration and continues with the next iteration. The syntax of continue statement is:

while condition:
    # Code block
    if condition_to_skip:
        continue
    # More code

# Example: Using a while loop with continue statement to skip printing even numbers.
count = 1

while count <= 5:
    if count % 2 == 0:
        count += 1
        continue
    print(count)
    count += 1

else clause in python loop

In Python, the else clause can be used with loops (including for and while loops) to execute a block of code when the loop completes normally, i.e., when the loop condition becomes false. The else block is executed after the loop finishes its iterations, but not if the loop is terminated prematurely by a break statement. Here's an example to illustrate how the else clause works with a for loop:

python code: Using a for loop with else clause to find if a number is prime

# Example: Using a for loop with else clause to find if a number is prime
num = 17

for i in range(2, num):
    if num % i == 0:
        print(num, "is not a prime number")
        break
else:
    print(num, "is a prime number")

In the above example, we want to check if the number num is prime.

  • The for loop iterates over the range from 2 to num - 1 (exclusive).
  • Inside the loop, we check if num is divisible by i. If it is, we print that num is not a prime number and exit the loop using break.
  • If the loop completes all iterations without encountering a break, it means num is not divisible by any number in the range, and hence it is a prime number.
  • In this case, the else block is executed, and we print that num is a prime number.