× Introduction Working with Python Basics Data Types Control statements Loops Functions Lists Tuples Strings Turtle eBooks

Loops (Repeat a sequence of statements)

Probably the most powerful thing about computers is that they can repeat things over and over very quickly. There are several ways to repeat things in Python, the most common of which is the for loop.

Looping constructs provide the facility to execute a set of statements in a program repetitively, based on a condition. The statements in a loop are executed again and again as long as particular logical condition remains true. This condition is checked based on the value of a variable called the loop’s control variable. When the condition becomes false, the loop terminates. It is the responsibility of the programmer to ensure that this condition eventually does become false so that there is an exit condition and it does not become an infinite loop.

The 'For' Loop

The for statement is used to iterate over a range of values or a sequence. The for loop is executed for each of the items in the range. These values can be either numeric, or, as we shall see in later chapters, they can be elements of a data type like a string, list, or tuple.

With every iteration of the loop, the control variable checks whether each of the values in the range have been traversed or not. When all the items in the range are exhausted, the statements within loop are not executed; the control is then transferred to the statement immediately following the for loop. While using for loop, it is known in advance the number of times the loop will execute.

Syntax of the for Loop:

for  in :
  statement(s)

Example 1:

#Print the characters in word PYTHON using for loop
for letter in 'PYTHON':
       print(letter)

Example 2:

#Print the given sequence of numbers using for loop
count = [10,20,30,40,50]
for num in count:
  print(num)

Example 3:

#Print even numbers in the given sequence
numbers = [1,2,3,4,5,6,7,8,9,10]
for num in numbers:
  if (num % 2) == 0:
  print(num,'is an even Number')

The Range() Function

The range() is a built-in function in Python.

Syntax of range() function is:

range([start], stop[, step])

It is used to create a list containing a sequence of integers from the given start value upto stop value (excluding stop value), with a difference of the given step value. We will learn about functions in the next chapter. To begin with, simply remember that function takes parameters to work on. In function range(), start, stop and step are parameters.

The start and step parameters are optional. If start value is not specified, by default the list starts from 0. If step is also not specified, by default the value increases by 1 in each iteration. All parameters of range() function must be integers. The step parameter can be a positive or a negative integer excluding zero.

Example:

 #start and step not specified 
>>> list(range(10)) 
   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

#default step value is 1 
>>> list(range(2, 10))
 [2, 3, 4, 5, 6, 7, 8, 9] 
#step value is 5 
>>> list(range(0, 30, 5)) 
[0, 5, 10, 15, 20, 25] 
#step value is -1. Hence, decreasing 
#sequence is generated 

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

The function range() is often used in for loops for generating a sequence of numbers.

Example:

#Print multiples of 10 for numbers in a given range
for num in range(5): 
    if num > 0: 
        print(num * 10)

While loop

A while loop executes statements repeatedly as long as a condition remains true.The control condition of the while loop is executed before any statement inside the loop is executed. After each iteration, the control condition is tested again and the loop continues as long as the condition remains true. When this condition becomes false, the statements in the body of loop are not executed and the control is transferred to the statement immediately following the body of while loop. If the condition of the while loop is initially false, the body is not executed even once.

The syntax for the while loop is:

     while test-condition:
        # Loop body
        Statement(s)

Example:

count = 1
while count <= 5:
  print(count)
  count += 1

Break and Continue Statement

Looping constructs allow programmers to repeat tasks efficiently. In certain situations, when some particular condition occurs, we may want to exit from a loop (come out of the loop forever) or skip some statements of the loop before continuing further in the loop. These requirements can be achieved by using break and continue statements, respectively. Python provides these statements as a tool to give more flexibility to the programmer to control the flow of execution of a program.

Break Statement

The break statement alters the normal flow of execution as it terminates the current loop and resumes execution of the statement following that loop. break keyword breaks out of a loop.

Example:

num = 0
for num in range(10):
  num = num + 1
  if num == 8:
    break
  print('Num has value ' + str(num))
print('Encountered break!! Out of loop')

Continue Statement

When a continue statement is encountered, the control skips the execution of remaining statements inside the body of the loop for the current iteration and jumps to the beginning of the loop for the next iteration. If the loop’s condition is still true, the loop is entered again, else the control is transferred to the statement immediately following the loop. Continue breaks out of an iteration.

Example:

#Prints values from 0 to 6 except 3
num = 0
for num in range(6):
    num = num + 1
    if num == 3:
       continue
    print('Num has value ' + str(num))
print('End of loop')

Nested Loops

A loop may contain another loop inside it. A loop inside another loop is called a nested loop.

Example:

#Program to print the pattern for a number input by the user
#The output pattern to be generated is
#1
#1 2
#1 2 3
#1 2 3 4
#1 2 3 4 5
num = int(input("Enter a number to generate its pattern = "))
for i in range(1,num + 1):
  for j in range(1,i + 1):
    print(j, end = " ")
  print()

Example Programs

1.Ask the user to enter their name and then display their name three times.

name = input("Enter your name: ")
for num in range(0,3):
    print(name)

OUTPUT:
Enter your name: Sri rama
Sri rama
Sri rama
Sri rama

2.Alter the above program so that it will ask the user to enter their name and a number and then display their name that number of times.

name = input("Enter your name: ")
number = int(input("Enter a number: "))
for num in range(0,number):
    print(name)

OUTPUT:
Enter your name: python
Enter a number: 5
python
python
python
python
python

3.Change the above program to also ask for a number. Display their name (one letter at a time on each line) and repeat this for the number of times they entered.

name = input("Enter your name: ")
number = int(input("Enter a number: "))
for num in range(0,number):
    for i in name:
        print(i)

OUTPUT:
Enter your name: Ram
Enter a number: 2
R
a
m
R
a
m

4.Write a program to print the table of a given number. The number has to be entered by the user.

number = int(input("Enter the number to display its table:  "))
for num in range(1,12):
    print(number, " x " , num , " = ", number*num)

OUTPUT:
Enter the number to display its table:  6
6  x  1  =  6
6  x  2  =  12
6  x  3  =  18
6  x  4  =  24
6  x  5  =  30
6  x  6  =  36
6  x  7  =  42
6  x  8  =  48
6  x  9  =  54
6  x  10  =  60

5.Write a program to print the table of a given number. The number has to be entered by the user.

number = int(input("Enter the number to display its table:  "))
for num in range(1,12):
    print(number, " x " , num , " = ", number*num)

OUTPUT:
Enter the number to display its table:  6
6  x  1  =  6
6  x  2  =  12
6  x  3  =  18
6  x  4  =  24
6  x  5  =  30
6  x  6  =  36
6  x  7  =  42
6  x  8  =  48
6  x  9  =  54
6  x  10  =  60

6.Write a program that prints the minimum and maximum of five numbers entered by the user.

smallest = 0
largest = 0
for i in range(0,5):
    x = int(input("Enter the number: "))
    if i == 0:
        smallest = largest = i
    if(i < smallest):
        smallest = i
    if(i > largest):
        largest = i
print("The smallest number is", smallest)
print("The largest number is ", largest)

OUTPUT:
Enter the number: 58
Enter the number: 89
Enter the number: 95
Enter the number: 62
Enter the number: 58
The smallest number is 58
The largest number is  95

7.Write a program to find the sum of digits of an integer number, input by the user.

sum = 0
n = int(input("Enter the number: "))
while n > 0:
    digit = n % 10
    sum = sum + digit
    n = n//10
print("The sum of digits of the number is",sum)

OUTPUT:
Enter the number: 589
The sum of digits of the number is 22

8.Write a program that checks whether an input number is a palindrome or not. [Note: A number or a string is called palindrome if it appears same when written in reverse order also. For example, 12321 is a palindrome while 123421 is not a palindrome.

rev = 0
n = int(input("Enter the number: "))
# Storing the number input by user in a temp variable to run the loop
temp = n
# Using while function to reverse the number
while temp > 0:
    digit = (temp % 10)
    rev = (rev * 10) + digit
    temp = temp // 10
# Checking if original number and reversed number are equal
if (n == rev):
    print("The entered number is a palindrome.")
else:
    print("The entered number is not a palindrome.")

OUTPUT:
Enter the number: 12321
The entered number is a palindrome.

9.Write a program using while loop to generate addition quiz. It sholud have an option to choose play again.

import random
choice = 'y'
while choice == 'y':
   # Generate random numbers
   number1 = random.randint(0, 9)
   number2 = random.randint(0, 9)

   # Prompt the user to enter an answer
   answer = eval(input("What is " + str(number1) + " + " + str(number2) + " ? "))

   if answer == number1 + number2:
       print("Correct! " + str(number1) + " + " + str(number2) + " = ", number1 + number2 )
   else:
       print("Wrong! " + str(number1) + " + " + str(number2) + " = ", number1 + number2)
   choice = input("Do you want to play again? y/n ")

OUTPUT:
What is 9 + 0 ? 9
Correct! 9 + 0 =  9
Do you want to play again? y/n y
What is 8 + 1 ? 9
Correct! 8 + 1 =  9
Do you want to play again? y/n n

10.Write a program to generate number guessing game.

import random
number = random.randint(0, 10)
print("Guess a magic number between 0 and 10")
guess = -1
while guess != number:
   # Prompt the user to guess the number
   guess = eval(input("Enter your guess: "))

   if guess == number:
      print("Yes, the number is", number)
   elif guess > number:
      print("Your guess is too high")
   else:
      print("Your guess is too low")

OUTPUT:
Guess a magic number between 0 and 10
Enter your guess: 7
Your guess is too high
Enter your guess: 5
Your guess is too high
Enter your guess: 3
Yes, the number is 3