While Loop In Python

Introduction

Python is now the most popular programming language because it is free and open-source, has a large standard library, and can be readily coupled with several programming languages. Among other elements, there are three types of loops in Python: 

  1. While loops
  2. For loops
  3. Nested loops

 

This article entails basic looping statements, i.e., while loop in Python and other statements and expressions used with while loop.

 

While Loop in Python

Python’s while loop statement is used to execute statements repeatedly (s). As the number of times the while syntax in Python runs is not known ahead of time, the while loop in Python is referred to as an Infinite Iteration statement. It will continue to execute repeatedly until the condition is true, and it will stop only if it turns false.

 

Assume you are instructed to print your favorite fruit name 50 times in Python. The most ignorant way would be to execute the statement print(“FruitName”) 50 times. But that’s a needless effort with 50 lines of code.

 

You will get the best outcomes if you utilize the while loop in Python. This is how it executes: Create a while loop, add the print(“FruitName”) within the while loop, add a condition that passes after 100 executions, and you’re done.

 

Unlike the droning approach, which requires 100 statements, this code is just 5-6 statements long. In simple words, the while syntax in Python simplifies our lives.

  • Syntax
  • while expression:
  • statement(s)

 

Here is a description of the elements in while syntax in Python:

 

  • Statement(s): Can be a single statement or a set of statements indented evenly. Python considers consistently nested statements to be a block.
  • Expression: In Python, an expression is a statement assessed as True or False in the condition statement. Python considers all non-zero numbers to be true and 0 or None to be false. In comparison, the loop continues to run as long as the expression returns True. It will terminate when the expression returns False. 
  • While: The keyword while is used to create a loop statement. The while expression is the head/beginning of the while loop statement, and the statement(s) evenly positioned comprises the loop’s body.

 

Working of While Loop in Python:

  • The expression is first checked. If it returns true, control is given to the while loop’s subsequent statement(s).
  • All statements positioned to the right of the while loop for the while loop’s body are run.
  • After the statements are run, control is transferred back to the expression, which is then assessed again. If true, the body is executed again. This process is repeated until the expression returns false.
  • Control is handed to another line of the while loop when the while loop is terminated.

 

While Loop in Python Flowchart

 

Image Title: While loop flowchart in Python

Image Content: While loop, false, conditions true?, true, body of while loop execute statements, exit while loop

Image source: http://www.trytoprogram.com/images/python_while_loop.jpg

Example of while loop in Python 

Program to print a favourite fruit seven times using the while loop in Python 

add = 0;

while add < 7:

print(“My favourite fruit is mango”)

count = 1

Output:

My favourite fruit is mango

My favourite fruit is mango

My favourite fruit is mango

My favourite fruit is mango

My favourite fruit is mango

My favourite fruit is mango

My favourite fruit is mango

 

Explanation:

  • The purpose is to print the “My favourite Fruit is Mango” string 7 times.
  • We created a variable add and initialised it to 0
  • The expression ‘add< 7’ is assessed, and as 0 < 7, control goes in the body of the while loop.
  • The add = 1 line and the ‘print’ statement are run equitably from the body of the while loop. The string is printed to the output, and the value is increased from 0 to 1.
  • Control is now returned to the expression ‘add 7. Since 1 <7, control has returned to the while loop.
  • This operation is continued until the ‘add’ value is 7 and the print statement has been run seven times.
  • As condition 7 <7 returns false, the loop stops, the body of the while loop is not run, and the control moves to the statement after the while statement.

 

While Loop With Else

Python also allows else statements in combination with while statements and the else statement is not mandatory. The following cases illustrate how while else works:

  • When the while expression returns False, the statement given after it will run.
  • After the while statement has been executed, the else statement will run.
  • If a break statement is run within the while loop and the execution is terminated, the else block is bypassed, and control passes to the statement below the while…else.
  • The differences between the sentences within the else block and those put below the while…else.
  • If the while loop ends unexpectedly, the statements inside the else block will be skipped. If the while statement returns false, the else statement is performed.
  • The statements following the while..else will run in both cases- when the while expression returns false and when the while expression terminates abruptly.

 

While Syntax in Python

while expression:

 statement(s)

else:

 

Statement(s)

The body of ‘else’ can be one statement or a block of statements with consistent indentation. After the while loop condition returns false and the loop is ended, the else statement is run just once.

 

Example:

add = 0;

while add < 8:

 print(“My favourite fruit is mango”)

 add = 1

else:

 print(“Favourite fruit is printed eight times.”)

 

Output:

My favourite fruit is mango

My favourite fruit is mango

My favourite fruit is mango

My favourite fruit is mango

My favourite fruit is mango

My favourite fruit is mango

My favourite fruit is mango

My favourite fruit is mango

Favourite fruit is printed eight times.

 

Explanation:

  • The purpose is to print the “My favourite Fruit is Mango” string eight times.
  • We used a variable add and initialised it to 0
  • The expression ‘add < 8’ is assessed, and as 0 < 8, control runs inside the while loop
  • The add = 1 line and the ‘print’ statement are run equitably from the body of the while loop. The string is printed to the output, and the value is increased from 0 to 1.
  • Now, control goes again to the expression ‘add< 8’. And as 1 < 8, control again runs inside the while loop.
  • This operation is continued until the ‘add’ value is 8 and the print statement has been run eight times.
  • Now, as condition 8 <8 returns false, the loop stops, the body of the while loop is not run, and the control moves to the statement after the while statement, which is the else statement.
  • The body of else statements is now executed, followed by the print statement.
  • The control flow then passes to the next statement, following the while-else statement.

 

Single Statement While Loop in Python

If the while loop’s body has only one statement, it can be inserted on the same line as the while header statement. Python supports this variant. The while syntax in Python below demonstrates:

while expression: statement

This is only permitted for a single statement. If there are many statements, they must be written within the body of the while loop and evenly nested.

Example:

add = 0

while add< 6: print(“I’m Alexa”)

Output:

The String “I’m Alexa” is printed indefinitely on the terminal.

Explanation:

  • The add is initialised to 0
  • The expression adds < 6 is assessed, and the single statement inside the body is executed.
  • The control then goes to the expression add < 6, and it returns true.
  • This procedure runs infinitely, as add < 6 will never return false as we are not changing the added value anywhere.
  • So this loop is called indefinite loop python. Let us define and comprehend what is an indefinite loop Python.

 

The Indefinite While Loop in Python

The indefinite loop in Python is a loop that never ends since the expression (condition) stated in the while header will never return False. The instance in the next section is an example of an endless while loop.

In programming, there are several applications for the Infinite while loop. A basic example is a system/software that runs continuously, such as a server program. As a result, the client software can connect to the server program at any moment as long as the server program is functioning.

Let us look at an example indefinite loop Python program

add = 0

while add != 1:

 name = str(input(“Your favorite color is? “))

 print(“My favorite colour is” name)

Output:

Your favorite colour is? Black

My favorite colour is Black

Your favorite colour is? Blue

My favorite colour is Blue

Your favorite colour is? Grey

My favorite colour is Grey

Your favorite colour is? Black (recent call last):

    File “main.py”, line 3, in <module>

      name = str(input(“Your favourite color is? “))

KeyboardInterrupt

Explanation:

  • The expression add!= 1 is always true in this case. As a result, the while loop’s body runs on infinite.
  • This loop continues to ask for input and output the value until we press CTRL C, which triggers a keyboard interrupt to terminate the loop.

 

While Loop Control Statements in Python

Loop control statements in Python control the sequence of execution of a while loop. They impede the usual execution of a loop. Python supports the following loop control statements:

 

Continue Statement:

Continue statement in the while loop body returns the flow of control to the expression in the header, bypassing the operation of other statements inside the body.

Example:

addition = 0

while addition < 10:

 addition = 1;

 if(addition == 5): continue

 print(“The total is ” str(addition))

Output:

The total is 1,

The total is 2

The total is 3

The total is 4

The total is 5

The total is 6

The total is 7

The total is 8

The total is 9

The total is 10

 

Explanation:

  • The addition is initialized to 0
  • Addition < 10 is assessed, and the body of the while is run.
  • When the addition is = = 5. The if statement condition addition== 5 will be true. And the statement ‘continue’ is run.
  • Once the ‘continue’ statement runs, control goes to the while header again, bypassing all the statements. Hence the print statement “The total is..” is not executed in the case of addition == 5
  • After the addition becomes 6 again, the control sequence is similar to the while loop.

 

Break Statement:

Break statement in the body of a while loop will terminate the continues and get the control out of the loop. It is like an abrupt force stop of a while loop. If it is a while..else statement, the else part is also terminated when a break statement is run. Control is given to the statement after the while..else statements.

Example:

addition = 0

while addition < 10:

 addition = 1;

 if(addition == 5): break

 print(“The addition is ” str(addition))

Output:

The addition is 1

The addition is 2

The addition is 3

The addition is 4

Explanation:

  • The addition is initialised to 0
  • Addition < 10 is assessed, and the ‘while’ body is run.
  • When the value of addition is equal to 5. The if statement condition addition == 5 will be true. And the break statement is run.
  • When the break statement is run, control exits the while loop promptly, bypassing all statements below it, and the loop’s repeated execution ends. As a result, no values equal to or less than five were displayed.

 

Difference Between For and While Loop in Python 

Let us know the difference between for and while loop in Python:

 

Basis For loop While loop
Declaration for value in range:

<statement>

while condition:

<statement>

Use loop The loop is used when we know the number of iterations. The loop is used when we don’t know the number of are required.
Condition body of the for loop will be executed indefinitely if there is no condition. if the condition is missing, then it gives an error.
Iteration The statement is written at the top. Statements can be written anywhere in the loop body.
Operational process control goes to the condition and checks the items from the sequence. It will terminate the statement and start again and check from the range it will choose the next value and run the statement and it will terminate until the range becomes zero. Control will check inside the loop when while condition is true, if the condition is true, it will terminate the body and again check the condition.
Initialization If the condition is not true, control will not enter the loop. if the condition is true, the loop is iterated.
Examples: alphabet = [‘e’,’f’,’g’]

for y in alphabet:

print(y)

a =4

while a < 8:

print(a)

a = 1

 

Conclusion

One of the many stages in mastering this exciting and powerful programming language is understanding the while loop in Python. Understanding Python opens the door for new opportunities in your professional career as big data and business analytics are widely welcomed across all domains.

Related Articles

} }
Request Callback