Python Loops and basic examples for the beginners

Hello readers, welcome back to know Python Loops and its basic examples. Python loops are called as Control Flow Statements. Let us see in this article what are the possible type of loops exists in python and their real-time use in the applications.

Python Loops:

  • For Loop
  • While Loop

Let us dive into control flow statements and how it is handled in the program.

Python ‘for’ Loop:

In generic, a loop is called a control structure that repeats a block of instructions. The ‘for’ loop is a loop that repeats the instruction block a pre-determined number of times. The repeating instruction block is usually called the body of the loop and each repetition is usually called an iteration.

Basic Syntax of ‘for’ loop or Python loop is written:

for variable in iterableElement(list,string,range,dict):
body of the for loop

It is not actually necessary to define the control variable before the loop as ‘variable’ written in the above syntax, although a variable which is already defined in the program can be used as a control variable.

Python loops

We are going to make an example in which the program performs a certain number of times some operation.

This type of structures in programming languages are called loops or Python Loops and usually, there are two types:

  1. Loops that have a control variable that takes a set of values
  2. The loops that are repeated while a certain condition is met

This time we will make a loop of the first type, that is, our loop will repeat a certain number of times and will have a control variable that will change the value in each of the repetitions.

>>> print ('Example of for loop')
Example of for loop
>>> for i in [1,2,3,4,5]:
    print ('This is the repetition value', i) 
This is the repetition value 1
This is the repetition value 2
This is the repetition value 3
This is the repetition value 4
This is the repetition value 5

The explanation for the above code using Python ‘for’ Loop or Python Loop:

We can check now as for how the instruction, print (‘This is the repetition value’, i) is repeated 5 times and in each of them, the value of i is one of the values mentioned in the list which are included in the declaration of the ‘for’ loop.

In the program ‘i’ is the control variable of the for loop that traverses the list of values.

This is an example which is defined with an empty list and let’s see how the execution takes place.

>>> print("Example where the list is declared empty")
Example where the list is declared empty
>>> for i in []:
    print("This is the iteration value ", i) 
>>> print("Final statement after Python Loops")
Final statement after Python Loops

This is the new example as a variable can be declared in the program before assigning to a loop.

>>> i = 10
>>> print(" The loop has not started. Now i value {i}")
 The loop has not started. Now i value {i}
>>> print(f" The loop has not started. Now i value {i}")
 The loop has not started. Now i value 10
>>> for i in [0, 1, 2, 3, 4]:
    print(f"{i} * {i} = {i ** 2}")

    
0 * 0 = 0
1 * 1 = 1
2 * 2 = 4
3 * 3 = 9
4 * 4 = 16
>>> print(f"The loop is over. Now i value {i}")
The loop is over. Now i value 4

Description for the above code:

The control variable can be a variable used before the loop. The value that the variable had does not affect the execution of the loop, but when the loop ends, the control variable retains the last assigned value.

This time we will make a loop of the second type as we discussed in the above.

>>> print ('Example of for loop using range function')
Example of for loop using range function
>>> for i in range (1,6):
    print ('This is the repetition value', i)

    
This is the repetition value 1
This is the repetition value 2
This is the repetition value 3
This is the repetition value 4
This is the repetition value 5

On this occasion, we have used the range function (1,6) that facilitates an iterable object to be traversed by the loop.

Note that of the 2 values provided to the range function, the first one would be the start of the iterable elements, but the second one is the limit of the iteration, hence we have put 6 instead of 5, so that it also includes the value 5.

This allows the number of iterations to depend on the development of the program. In the following example, the user decides how many times the loop is executed.

>>> iteration_num = int(input("Enter an iteration number = "))
Enter an iteration number = 5
>>> for i in range(iteration_num):
	print(f"Hello {i}")

	
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4

Python ‘while’ loop:

The ‘while’ loop allows the user to repeat the execution of a group of instructions while a condition is met that is, while the condition has the value True.

Declaration of the syntax of ‘while’ loop:

while condition:
    body of the loop

When the control reaches a while loop, Python evaluates the condition first and, if it is true,  it executes the body of the loop. Once the body of the loop is executed, the process is repeated (the condition is evaluated again and, if true, the body of the loop is executed again and again as long as the condition is true). Only when the condition is false, the body of the loop will not be executed and control comes out from the loop and executes the rest of the program.

The variable or variables that appear in the condition are usually called control variables. Control variables must be defined before the while loop and modified in the while loop.

The advantage of a while loop is that the control variable can be modified with greater flexibility, as in the following example:

>>> i = 1
>>> while i <= 50: print(i) i = 3*i + 1 >>>print(‘Program Finished’)
1
4
13
40
Program Finished

Infinite Loops:

If the condition of the loop is always true, the loop will never end and we will have what is called an infinite loop. Although it is sometimes necessary to use infinite loops in a program, they are usually due to errors that must be corrected.

Moreover, unintended infinite loops should be avoided as they mean losing control of the program. To interrupt an any infinite loop, press the key combination Ctrl+C and it also depends on the interpreter or IDE which you use. When you interrupt a program, an error message similar to this one will be displayed as ‘KeyboardInterrupt’ error.

Example for the Infinite Loop:

>>>i = 1
>>>while i <= 10:
print(i, end=" ")

1111111111111111111……..

The Examples which are showed in the for loop are also implemented in the ‘while’ loop. This implementation may be as a good practice for you.

If any doubts please feel free to comment. If you like this Python Loops article please share to python readers.

click here to install Python on Windows through step by step guidelines.

Python Loops and basic examples for the beginners
4 (80%) 2 votes

Reply