while loop with python

While loop in python

Introduction

“Life is a loop, you get back what you give”

Hello people, hope now you are clear with conditional branching. In this article, we will discuss in detail about loops in python.

Loops

In English, the loop is a shape that bends around and crosses itself.

This is an image of a loop in general.

In programming, we mention a loop as a set of instructions that should be repeated.

Types

In order to implement the concept of loops in python, we have three different kinds of loops available.

  • While loop
  • For loop
  • Nested loop

While loop

In python, a while loop is used to execute a set of statements until a condition is satisfied.

For example, in a billing counter, we bill the products and get the total until we have items to be billed. Here, the condition we are checking is if there are more items available, till the items are available, we will be adding the total and we will quit the process once the items are over.

In short, a while loop is used when you don’t know how many times the loop should be executed.

Syntax

while <condition>:
   Statemnts to be repeated

The controlling expression, <condition>, typically involves one or more variables that are initialized prior to starting the loop and then modified somewhere in the loop body.

The <condition is evaluated and returns a boolean value, if it returns true then the loop is executed and again evaluates the condition and if it returns false then code outside the loop is executed.

See also  OBJECT ORIENTED PROGRAMMING (OOP’s) IN PYTHON

Example

n=5
while n>=0:
	print(n)
	n=n-1
print("Thank you")
5
4
3
2
1
0
Thank you

In the above code snippet, 

  • Line 1, initializes the n value to be equal to zero.
  • Line 2, checkers if the condition is True, if the condition is true line 3,4 will be executed where we are printing the value of n and decrementing the n value by 1. Again we check the condition, this is repeated until the condition is satisfied.
  • Once the condition becomes False, Line 5 will be executed to print Thank you.

Flow chart

flow chart for while loop

Loop control statement

Till now, we have seen that a loop will be executed completely without any break in between. Python provides two different statements to terminate the loop whenever required. They are,

  • Break statement
  • Continue statement

Break statement

Whenever a break statement is encountered inside a loop, the loop will be broken and the control comes out of the loop and executes the line which is next to the loop.

Continue statement

Whenever a continue statement is encountered the current iteration will be terminated and the control goes to the place back for checking the condition to be satisfied.

Flow chart explaining break and continue statement

flow chart for break and continue

Example for break statement

n=5
while n>=0:
	if n==3:
		Break
	print(n)
	n=n-1
print("Thank You")

Output

5
4
Thank you

In the above code snippet, 

  • In line 1, we initialise the the value of n to 5
  • In like 2, we enter the while loop and checks the condition, now n = 5, so the condition is True. In line 3, we are checking the value of n is equal to 3, but since it is false we are printing the n value and decrementing the value of n. 
  • The same happens for n=4.
  • Now when n value becomes 3, we check the condition in line 3 and the condition satisfies so break statement is executed. Once we encounter break statement we will come out of the loop and execute line 7 to print Thank you.
See also  50+ Best python projects with source code [2023]

Example of continue statement

n=5
while n>0:
	n=n-1
	if n ==3:
		continue
	print(n)
print("Thank you")

Output

4
2
1
0
Thank you

In the above code snippet, 

  • In line1, we initialize the value of n to 5.
  • In line2, we enter the while loop and check the condition, now n = 5, so the condition is True. In line 2, we are decrementing the value of n.In line 3, we are checking the value of n is equal to 3, but since it is false we are printing the n value and decrementing the value of n. 
  • The same happens for n=4.
  • Now when the n value becomes 3, we check the condition in line 3 and the condition satisfies so the continue statement is executed. So, the control goes to line 2 again and checks the condition and decrements the value, and continues the loop.
  • After the whole loop is executed we print thank you.

The else clause

Python allows an optional else clause at the end of the while loop. This is a unique feature in python which is not found in most programming languages.

This else statement will be executed only if the loop terminates naturally. This else will not be executed if the loop terminates after encountering a break statement.

Syntax

while <condition>:
	Statement
else:
	<additional statement> 

Infinite loop

Infinite loops are loops that will not be coming out of the program means that never ends. 

Syntax:

while True:
	<statements>

In the code snippet, the statements are executed infinite times, because no way we can come out of the loop because True can never become False.

But, this loop can be broken with the help of a break statement.

We can use this infinite loop, with help of a break statement for efficient programming.

We can use multiple break statements, so if we need to break the loop in many conditions we can use this kind of infinite loop, instead of writing conditions on the top of the line.

See also  Tuples in python

Nested loops

We can write more than one while loop inside another loop/ conditional statements.

The break and continue statement is applicable for the nearest enclosing loop.

Syntax

while <condition1>:
    statement
    statement
    while <condition2>:
        statement
        statement
        break  # Applies to while <condition2>: loop
    break  # Applies to while <condition1>: loop

Example

#Write a program for fast billing counter.
#Get the price of the item from the user and display the total after each item. Since it is the fast counter more than 10 items are not allowed.
#Ask the user if they have more items to be added and add accordingly.
items_count=0
total=0
while True:
  price=int(input("Enter the price of the item: "))
  total=total+price
  items_count += 1
  print("The total amount is ", total)
  if items_count==10:
    print("Please pay ", total,"\nThanks for shopping. \nVisit again")
    break
  else:
    do_you=int(input("Do you want to add more items? \nPress 1 for yes \nPress 2 for no : "))
    if do_you==1:
      continue
    elif do_you==2:
      print("Please pay ", total,"\nThanks for shopping. \nVisit again")
      break
    else:
      print("Please enter correct option.")
      break

Practice yourself

  • In the previous practice yourself you have written a program for ATM machines, now update that program such that the user can do up to two transactions in the machine.
  • Print numbers from 1 to 100 except the numbers which are multiples of 7.
  • Print average marks of 5 subjects and ask if they need to find the average again.
  • Display the product of numbers from the user until the user presses 0.

Conclusion

Thus, I guess you got a clear idea about the while loop. Practice more for encountering different scenarios and comment if encountering any problems.

2 thoughts on “While loop in python”

  1. Pingback: For loop in python -

  2. Pingback: Rock Paper Scissor Game in python -

Leave a Comment

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

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

we provide projects, courses, and other stuff for free. in order for running we use Google ads to make revenue. please disable adblocker to support us.