Previous Index Next

Looping Structures

It is also called a repetitive control structure. Sometimes we require a set of statements to be executed a number of times. This type of program execution is called looping. Python provides the following construct

  • while loop
  • for loop

The while Loop

Here is the general format of the while loop in Python. Statement written inside while statement will execute till condition remain true:

while condition:
   statement
   statement
   etc.

Program (repeat_message.py)

# This program print message 5 times.

i = 1
while i <= 5:
    print("I love programming in Python!")
    i = i + 1

Output:

I love programming in Python!
I love programming in Python!
I love programming in Python!
I love programming in Python!
I love programming in Python!

Program (print_natural.py)

# This program print n natural numbers.

n = int(input('Enter the value of n: '))
i = 1
while i <= n:
    print(i, end=' ')
    i = i + 1

Output:

Enter the value of n: 6
1 2 3 4 5 6

while loop

Program (sum_ numbers.py)

# This program calculates the sum of numbers entered by the user.

i = 1
sum = 0
n = int(input('How many numbers you want to enter? '))

while i <= n:
    num = int(input('Enter a number: '))
    sum = sum + num
    i = i + 1

print('The total is', sum)

Output:

How many numbers you want to enter? 4
Enter a number: 10
Enter a number: 5
Enter a number: 3
Enter a number: 7
The total is 25

The for Loop

A for loop is used for iterating over a sequence. You can generate a sequence using range function. The general format of range() function is like:

range (start, stop, step)

The range() function takes three arguments. Start and Step are the optional arguments. A start argument is a starting number of the sequence. If start is not specified it starts with 0. The stop argument is ending number of sequence. The step argument is linear difference of numbers. The default value of the step is 1 if not specified.

for i in range (10):
     print(i, end = ' ') 

Output:

0 1 2 3 4 5 6 7 8 9

Using the start parameter:

for i in range(2, 10):
    print(i, end = ' ')

Output:

2 3 4 5 6 7 8 9

Increment the sequence with step 3:

for i in range(3, 31, 3):
    print(i, end = ' ')

Output:

3 6 9 12 15 18 21 24 27 30

Program (backward_counting.py)

# This program prints backward counting

for i in range(5,0,-1):
    print(i)

Output:

5
4
3
2
1

Nested Loops

A loop that inside another loop is called a nested loop.

Program (print_pattern.py)

# This program prints pattern 

for i in range(1,4):
    for j in range(1,5):
        print(j, end = ' ')
    print()

Output

1 2 3 4 
1 2 3 4 
1 2 3 4

Previous Index Next