loops in python

Looping in Python-: Python provides a complete set of control-flow elements, with loops and conditionals. Sometimes we may need to alter the flow of the program. The execution of a specific code may need to be repeated several numbers of times.

Like any other language Python has 3 type Loops

  1. While Loops
  2. For Loops
  3. If else loops

While Loops in Python-: We can already use in python while loops. This syntax are

while condition:

The condition is a Boolean expression  is one that evaluates to a True or False value. As long as it is True the body is executed repeatedly. When the condition evaluates to False the while loop executes the post-code section and then terminates. If the condition starts out by being False the body would not be executed at all just the post-code section. The body and post-code are each sequences of one or more Python statements that are separated by newlines and are at the same level of indentation. The Python interpreter uses this level to delimit them. No other delimiters  such as braces or brackets are necessary.

while loops


Example and output of while Loops

while i<=5:  
Output of this programme


2. Python If else Statement -: Decision making is the most important aspect of almost all the programming languages. As the name implies  decision making allows us to run a particular block of code for a particular decision. The decisions are made on the validity of the particular conditions. Condition checking is the backbone of decision making.as like

if condition1:
elif condition2:
elif condition3:
elif condition(n-1):


It says  If condition1 is True, execute body1, if the condition first is false it check condition2 if condition2 is True execute body2. otherwise . . . and so on until it either finds a condition that evaluates to True or hits the else clause, in which case it executes body(n). As with the while loop the body sections are again sequences of one or more Python statements that are separated by newlines and are at the same level of indentation.

we do not need all that luggage for every conditional of course. we can leave out the else if parts the else part or both. If a conditional can’t find any body to execute (no conditions evaluate to True, and there’s no else part), it does nothing.

The body after the if statement is required. But we can use the pass statement here  The pass statement serves as a placeholder where a statement is needed   but it performs no action as like

a = int(input("Enter a? "));  
b = int(input("Enter b? "));  
c = int(input("Enter c? "));  
if a>b and a>c:  
    print("a is grater");  
if b>a and b>c:  
    print("b is grater");  
if c>a and c>b:  
    print("c is grater");

Output of this program

Enter a? 80
Enter b? 90
Enter c? 70
b is grater

For Loop in Python-: A for loop in Python is different from for loops in some other languages. The traditional pattern is to increment and test a variable on each iteration which is what C for loops usually do. A for loop iterates over the values returned by any iterable object that is any object that can yield a sequence of values.As like  a for loop can iterate over every element in a list a tuple or a string. But an iterable object can also be a special function called range or a special type of function called a generator or a generator expression which can be quite powerful. The syntax of for loops

for item in sequence:

When body is executed once for each element of sequence. item is set to be the first element of sequence and body is executed. then item is set to be the second element of sequence and body is executed and so on for each remaining element of the sequence.

Range function in for loop -:  When we need to loop with explicit indices. We can use the range command together with the len command on the list to generate a sequence of indices for use by the for loop. This code prints out all the positions in a list where it finds negative numbers as like …

x = [1, 3, -7, 4, 9, -5, 4]
for i in range(len(x)):
    if x[i] < 0:
        print("Found a negative number at index ", i)

In the number n range(n) returns a sequence 0, 1, 2, …, n – 2, n – 1. So passing it the length of a list produces a sequence of the indices for that list are elements. The range function does not  build a Python list of integers. it just appears to. It creates a range object that produces integers on demand. This is useful when we are using explicit loops to iterate over really large lists. Instead of building a list with 10 million elements in it. for example a bit of memory we can use range(10000000) which takes up only a small amount of memory and generates a sequence of integers from 0 up to (but not including) 10000000 as needed by the for loop.

Controlling range with starting and stepping values In python-: We can  use two variants on the range function to gain more control over the sequence it produces. If we use range with two numeric arguments the first argument is the starting number for the resulting sequence and the second number is the number the resulting sequence goes up to.

>>> list(range(3, 9)           1
[3, 4, 5, 6,7,8]
>>> list(range(2, 10))          1
[2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(5, 3))

Using break and continue in for loops -: The two special statements break and continue can also be used in the body of a for loop. If break is executed it immediately terminates the for loop and not even the post-code (if there is an else clause) is executed. If continue is executed in a for loop it causes the remainder of the body to be skipped over and the loop proceeds as normal

For loop and tuple unpacking-: We can use tuple unpacking to make some for loops cleaner. The following code takes a list of two-element tuples and calculates the value of the sum of the products of the two numbers in each tuple


whatlist = [(1, 2), (3, 7), (9, 5)]
result = 0
for t in whatlist:
    result = result + (t[0] * t[1])

Enumerate function-: We  can combine tuple unpacking with the enumerate function to loop over both the items and their index. This is similar to using range but has the advantage that the code is clearer and easier to understand. Like the previous example the following code prints out all the positions in a list where it finds negative numbers.

x = [1, 3, -7, 4, 9, -5, 4]
for i, n in enumerate(x):                                1
    if n < 0:                                            2
        print("Found a negative number at index ", i)    3

The zip function-: It is  useful to combine two or more iterables before looping over them. The zip function takes the corresponding elements from one or more iterables and combines them into tuples until it reaches the end of the shortest iterable.


Leave a Comment