Skip to content Skip to sidebar Skip to footer

A Loop That Continues to Execute Until the Entire Program is Interrupted

Control Flow Statements: Python While Loop

As discussed in the previous module, we know that Python, like other top programming languages, consists of some control flow statements. One of the control flow statements that we have already studied in the previous module is the Python if else statement. Another one of the control flow statements is loops. Loops are used when we want to repeat a block of code a number of times. In this module, we will learn about Python while loop.

Following is the list of all topics that we will cover in this module.

  • What Is While Loop in Python?
  • Infinite While Loop in Python
  • Do While loop in Python
  • While true in Python
  • Else with While Loop in Python
  • Python While Loop Interruptions
  • Number Pattern Program in Python using While Loop
  • Factorial Program in Python using While Loop

So, without any further delay, let's get started.

What Is a While Loop in Python?

While loop statements in Python are used to repeatedly execute a certain statement as long as the condition provided in the while loop statement stays true. While loops let the program control to iterate over a block of code.

Syntax of While Loop in Python:

while test_expression: body of while

The following flowchart explains the working of the while loop in Python.

python while loop

The program first evaluates the while loop condition. If it's true, then the program enters the loop and executes the body of the while loop. It continues to execute the body of the while loop as long as the condition is true. When it is false, the program comes out of the loop and stops repeating the body of the while loop.

Let's see the following example to understand it better.

a = 1   while( a<10): print(" loop entered", a, "times") a = a+1 print("loop ends here")   Output: loop entered 1 times loop entered 2 times loop entered 3 times loop entered 4 times loop entered 5 times loop entered 6 times loop entered 7 times loop entered 8 times loop entered 9 times loop ends here

Interested in learning Python? Enroll in our Python Course in London now!

Infinite While Loop in Python

Infinite while loop refers to a while loop where the while condition never becomes false. When a condition never becomes false, the program enters the loop and keeps repeating that same block of code over and over again, and the loop never ends.

The following example shows an infinite loop:

a = 1   while a==1: b = input("what's your name?") print("Hi", b, ", Welcome to Intellipaat!")

If we run the above code block, it will execute an infinite loop that will ask for our names again and again. The loop won't break until we press 'Ctrl+C'.

Output:

what's your name? Akanksha Rana #user input Hi Akanksha Rana , Welcome to Intellipaat!   what's your name? Amrit #user input Hi Amrit , Welcome to Intellipaat!   what's your name? Shubham #user input Hi Shubham , Welcome to Intellipaat!   what's your name? Traceback (most recent call last): #Stopped the loop by entering CTRL+C File "", line 2, in KeyboardInterrupt

Do While loop in Python

Python doesn't have a do-while loop. But we can create a program to implement do-while. It is used to check conditions after executing the statement. It is like a while loop but it is executed at least once.

          i = 1          while True:                    print(i)                                i = i + 1                      if(i > 5):                      break                      The output will be          1          2          3          4          5        

Now, take a look at our Python training for upgrading your career to new heights. Also, check out our free Python Interview Questions.

While true in Python

There is a concept of declaring a condition to be true, without evaluating any expression. This is done to indicate that the loop has to run until it breaks. We then write the break statements inside the code block.

The while true in python is simple to implement. Instead of declaring any Python variable, applying conditions, and then incrementing them, write true inside the conditional brackets.

          weeklySalary = 0          dayOfWeek = 1          week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]          while(True):                      if(week[dayOfWeek] == "Sunday"):                      print("Holiday!!")                      break                      weeklySalary += 2000                      dayOfWeek += 1          print(str(weeklySalary))          The output will be          Holiday!!          10000        

Else with the While Loop in Python

In Python, we can also use the else statement with loops. When the else statement is used with the while loop, it is executed only if the condition becomes false.

a = 1  while a<5: print("condition is true") a=a+1  else: print("condition is false now")

The example illustrates how the else statement works with the while loop.

Output:

condition is true condition is true condition is true condition is true condition is false now

In the above example, the program keeps executing the body of the while loop till the condition is true, meaning that the value of a is less than 5. Since the initial value of a is 1 and every time the program entered the loop the value of a is increased by 1, the condition becomes false after the program enters the loop for the fourth time when the value of a is increased from 4 to 5. When the program checks the condition for the fifth time, it executes it as false and goes to the else block and executes the body of else, displaying, 'condition is false now.'

Watch this video on 'Python Tutorial':

Python While Loop Python While Loop

Kick-start your career in Python with the perfect Python Course in New York now!

Python While Loop Interruptions

Python offers the following two keywords which we can use to prematurely terminate a loop iteration.

Break statements in While loop

  1. Break: The break keyword terminates the loop and transfers the control to the end of the loop.
Example: a = 1 while a <5: a += 1 if a == 3: break print(a) Output: 2

Continue statements in While loop

  1. Continue: The continue keyword terminates the ongoing iteration and transfers the control to the top of the loop and the loop condition is evaluated again. If the condition is true, then the next iteration takes place.

Example:

a = 1 while a <5: a += 1 if a == 3: continue print(a)  Output: 2 4 5

Go for the most professional Python Course Online in Toronto for a stellar career now!

Number Pattern Program in Python using While Loop

          n = int(input("Enter the number of rows: "))          i = 1          while i <= n:                      j = 1                      while j <= i:                      print("*", end = " ")                      j += 1                      print()                      i += 1          The output will be          Enter the number of rows: 4          *          **          ***          ****        

Factorial Program in Python using While Loop

          num = int(input("Enter a number: "))          fac = 1          i = 1          while i <= num:                      fac = fac * i                      i = i + 1          print("Factorial of ", num, " is ", fac)          The output will be          Enter a number: 4          Factorial of  4  is  24        

With this, we come to the end of this module on Python Tutorial. You can also go through this Python Data Science tutorial to know why Python is the most preferred language for Data Science. Also, check out our free Python Interview Questions.

Get 100% Hike!

Master Most in Demand Skills Now !

martinezwerseree.blogspot.com

Source: https://intellipaat.com/blog/tutorial/python-tutorial/python-while-loops/

Postar um comentário for "A Loop That Continues to Execute Until the Entire Program is Interrupted"