Python Loops – For, While, Nested Loops With Examples

Contents show

Python Loops – For, While, Nested Loops With Examples

Python Loops – For, While, Nested Loops With Examples
Python Loops – For, While, Nested Loops With Examples

LOOPING STATEMENTS

Python Loops


Python provides two kinds of loops : for loop and while loop to represent counting loop and conditional loop respectively.

1. The for loop

The for loop of Python is designed to process the items of any sequence, such as a list or a string, one by one.

The general form of for loop is as given below :

for <variable> in <sequence> :
      statements_to_repeat

For example, consider the following loop :

       for element in [10, 15, 20, 25]
               print(element + 2, end = ' ')

The above loop would give output as :
12 17 22 27

  • The above-given for loop executes a sequence of statements for each of the elements of given sequence [10, 15, 20, 25].
  • To keep the count, it uses a control variable(element in above case) in that takes a different value on each iteration. Firstly value 10, then the next value of sequence, 15, then 20 and lastly 25.

Q 1. Program to find the sum of of all numbers stored in a list.

[6, 5, 3, 8, 4, 2, 5, 4, 11]

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
	sum = sum+val

print("The sum is", sum)

The output of the program is :

The sum is 48

Python Loops

The range( ) based for loop


For number based lists, you can specify range( ) function to represent a list as in :

for val in range(3, 18) :
      print(val)

In the above loop, range(3, 18) will first generate a list[3, 4, 5, …, 16, 17] with which for loop will work. You need not define loop variable(val above) beforehand in a for loop.


As mentioned, a range( ) produces an integer number sequence. There are three ways to define a range :


range(stop) #elements from 0 to stop-1, incrementing by 1
range(start, stop) #elements from start to stop-1, incrementing by 1
range(start, stop, step) #elements from start to stop-1, incrementing by step

  • The start value is always part of the range. The stop value is never part of the range. The step shows the difference between two consecutive value in range.
  • If start value is omitted, it supposed to be 0. If the step is omitted, it is supposed to be 1.


Consider some examples of range( ) as given below :


range(7) 0, 1, 2, 3, 4, 5, 6
range(5, 12) 5, 6, 7, 8, 9, 10, 11
range(5, 13, 2) 5, 7, 9, 11
range(10, 4) no value
range(10, 4, -1) 10, 9, 8, 7, 6, 5

For example, the next program shows the cube of the numbers from 15 to 20 :


Program 1. Write a program to print cubes of numbers in the range 15 to 20.

for i in range(15, 21) :
      print("Cube of number", i, end = ' ')
      print("is", i**3)

1. Cube of number 15 is 3375
2. Cube of number 16 is 4096
3. Cube of number 17 is 4913
4. Cube of number 18 is 5832
5. Cube of number 19 is 6859
6. Cube of number 20 is 8000

Program 2. Write a program to print square root of every alternate number in range 1 to 10.

for i in range(1, 10, 2) :
       print("square root of", i, "is", (i**0.5))

program 3. find the out put of following code.

print(range(10))

print(list(range(10)))

print(list(range(2, 8)))

print(list(range(2, 20, 3)))

The output of code is :

range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]

range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]

program 4. Program to iterate through a list using indexing
genre = ['pop', 'rock', 'jazz']


genre = ['pop', 'rock', 'jazz']

# iterate over the list using index
for i in range(len(genre)):
	print("I like", genre[i])

The output of the program is :

I like pop
I like rock
​I like jazz

2. The while Loop

A while loop is a conditional loop that will repeat the instructions within itself as long as a conditional remains true (Boolean True or truth value true)


The general form of Python while loop is :

while <logicalExpression> :
       loop-body

Where the loop-body may contain a single statement or multiple statements or an empty statement (i.e., pass statement). The loop iterates while the logical Expression evaluates to true. When the expression become false, the program control passes to the line after the loop-body.


Program 5. Write a program that multiples two integer members without using the * operator, using repeated addition.

n1 = int(input("Enter first number :"))
n1 = int(input("Enter second number :"))
product = 0
count = n1
while count > 0 :
        count = count - 1
        product = product + n2
print("The product of", n1, "and", n2, "is", product)

Enter first number : 4
Enter second number : 5
The product of 4 and 5 is 20

program 6. Program to add natural number up to sum 1+2+3+……+n

n = int(input("Enter a number :))

# initialize sum and counter
sum = 0
i = 1

while i <= n:
    sum = sum + i
    i = i+1    # update counter

# print the sum
print("The sum is", sum)

The output of the program is :

Enter a number : 10

The sum is 55

In general, the while loop is used when it is not possible to know in advance how many times the loop will be executed, but the termination condition is known. The while loop is an entry-controlled loop as it has a control over entry in the loop in the form of test condition.

JUMP STATEMENTS – break AND continue


Python offers two jump statements – break and continue – to be used within loops to jump out of loop-iterations.


The break Statement


A break statement terminates the very loop it lies within. Execution resumes at the statement immediately following the body of the terminated statement.


Note :


A break statement skips the rest of the loop and jumps over to the statement following the loop.


The following figure (Fig 1.6) explains the working of a break statement.

the working of a break statement.
the working of a break statement.
The following code fragment gives you an example of a break statement :
a = b = c = 0
for i in range(1, 11):
      a = int(input("Enter number 1 :"))
      b = int(input("Enter number 2 :"))
      if b == 0 :
            print("Division by zero error1 Aborting!")
            break
       else :
            c = a/b
            print("Quotient = ", c)
print("Program over !")

Example to know more about break statement :

# Use of break statement inside the loop

for val in "string":
    if val == "i":
        break
    print(val)

print("The end")

The output of the program is :

s
t
r
The end

The above code fragment intends to divide ten pairs of numbers by inputting two numbers a and b in each iteration. If the number b is zero, the loop is immediately terminated displaying message ‘Division by zero error!’ otherwise the numbers are repeatedly input and their quotients are displayed.

The continue Statement


Unlike break statement, the continue statement forces the next iteration of the loop to take place, skipping any code in between.

NOTE :


The continue statement skips the rest of the loop statements and causes the next iteration of the loop to take place.

The following figure (Fig. 1.7) explains the working of continue

the working of continue statement
The following figure (Fig. 1.7) explains the working of continue

Program to know more about Python continue statement :

# Program to show the use of continue statement inside loops

for val in "string":
    if val == "i":
        continue
    print(val)

print("The end")

The output of the program is :

s
t
r
n
g
The end

Read More :-

Python if-elif-else statements

List Manipulation Class 11 Programs

dictionary in python examples practice

MORE ON LOOPS


There are two more things you need to know about loops-the loop else clause and nested loops.

1. Loop else Statement

Python loops have an optional else clause. Complete syntax of Python loops along with else clause is as given below :

for <variable> in <sequence> :                    
     statement1                                                       
     statement2                                                      
     :                                                                          
                                                                 else :                                                    statement(s)
while <test condition> :
     statement1                                                       
     statement2                                                        
     :                                                                          
                                                                 else :
     statement(S)                                                    

The else clause of a Python loop executes when the loop terminates normally, i.e., when test-condition results into false for a while loop or for loop has executed for the last value in the sequence; not when the break statement terminates the loop.


Following figure (1.8) shows you control flow in Python loops.

control flow in Python loops
Following figure (1.8) shows you control flow in Python loops.

Consider following example :

for a in range(1, 4) :
        if a%8 == 0:
              break
        print("Element is", end = ' ')
        print(a)
else :
       print("Ending loop after printing all elements of sequence")

The above program will give the following output :
1. Element is 1
2. Element is 2
3. Element is 3

Ending loop after printing all elements of sequence.
If, in above code, you change the line

          if a%8 == 0 :

with

          if a%2 == 0 :

Then the output will be :
Element is 1 <———————

Note that for a = 2, the break got executed and loop terminated. Hence just one element got printed(for a = 1). As break terminated the loop, the else clause also did not execute, so no line after the printing of elements.

Here is an example to learn more about for loop else statement :

digits = [0, 1, 5]

for i in digits:
    print(i)
else:
    print("No items left.")

The output of the program is :

0
1
5
No items left.

Here is an example to learn more about while loop else statement :


counter = 0

while counter < 3:
    print("Inside loop")
    counter = counter + 1
else:
    print("Inside else")

The output of the program is :

Inside loop
Inside loop
Inside loop
Inside else

2. Nested Loops

A loop may contain another loop in its body. This form of a loop is called nested loop. But in a nested loop, the inner loop must terminate before the outer loop.


The following is an example of a nested loop :

for i in range(1, 6) :
      for j in range(1, i) :
            print("*", end = ' ')
print( )

In nested loops, a break statement will terminate the very loop it appears in. That is, if break statement is inside the inner loop then only the inner loop will terminate and outer loop will continue. If however, the break statement is in outer loop, the outer loop will terminate.

Example 3: Use nested while loop to print stars(*) in patterns

Let’s use nested while loop to construct the following pattern:

*
* *
* * *
* * * *
def print_pattern(n):
    i = 0 # initialize to zero for outer loop
    j = 0 # initialize to zero for inner loop
 
    while i <= n:
        # outer loop runs n times
        while j < i:
            # inner loop runs i times
            print("*", end=" ")
            j += 1  # increment before checking inner loop condition
        j = 0       # re-initialize after leaving inner loop
        i += 1      # increment before checking outer loop condition
        print('')
 
 
if __name__ == '__main__':
    n = 5
    print_pattern(5)

The output of program is :

*
* *
* * *
* * * *

Python Loops – For, While, Nested Loops

Python Loops – For, While, Nested Loops With Examples

FAQ :-

Q 1. What are the 2 types of loops in Python?

ans. There are two types of loops in Python, for loop, while loop and nested loop.

Q 2. How do loops work?

ans. After the body of the ‘for’ loop executes, the flow of control jumps back up to the increment statement. .

If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition).

After the condition becomes false, the ‘for’ loop terminates.

Q 3. What is the difference between for loop and while loop?

ans. The ‘for’ loop used only when we already knew the number of iterations.

The ‘while‘ loop used only when the number of iteration are not exactly known.

If the condition is not put up in ‘for’ loop, then loop iterates infinite times. In ‘while‘ loop, the iteration statement can be written anywhere in the loop.

Q 4. Is a for loop or while loop faster?

ans. The For loop is slightly faster. For loop average about 2.95 to 3.02 ms. The While loop averaged about 3.05 to 3.37 ms.

Q 5. Why use a while loop instead of a for loop?

ans. In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *