While Loop in Python: Syntax and Use Cases

Updated on September 19, 2024

Article Outline

Loops are essential in every programming language, allowing you to execute the source code block repeatedly. Many loops, such as for and while loops, are available in Python.  The while loop is one of the most versatile and commonly used constructors in Python. This article explains the while loop in Python, covering its syntax, use case, and best practices.

What is While Loop in Python?

 

The Python while loop executes statements repeatedly. It allows you to repeatedly execute a source code block if a given condition is true, and it will stop repeating only if the conditions become false.

 

Suppose you want to print your name in Python 100 times. The most naive approach would be to type/paste the statement, print(“Name”) 100 times, and execute it. However, printing your name 100 times without using any loop is tedious.

 

The best possible approach will be to use the while loop statement in Python.

 

 

The following program demonstrates the while loop working.

 

Program

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

Output

1 2 3 4 5 6 7 8 9 10
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Syntax of While Loop in Python

while expression: statement(s)

 

Let’s understand the while loop syntax.

 

  • statement(s): It can be a single statement or a block of statements.
  • expression: It is a condition statement in Python. It is evaluated to be true or false. Python interprets all non-zero values as true and 0 or None as false. The while loop keeps repeating itself until the expression becomes false.
  • While: This keyword defines the while loop.

 

Working of while loop:

 

  • First, the expression will be evaluated. If it returns true, control is passed to the indented statements inside the while loop.
  • All the statements indented in the while loop of the body will be executed.
  • Once all statements are executed, control is again passed to the expression, and the expression is re-evaluated. If it returns true, the body is executed again. This repeats until the expression is false.
  • Once the while loop breaks, control is passed to the next unindented line of the while loop.

 

FlowChart of While Loop in Python

While Loop in Python

Example of Python While Loop

In this example, we will print the name 10 using the while loop in Python language.

 

Program

count = 0 while count < 10: print("Neeraj Kumar ") count += 1

Output

Neeraj Kumar Neeraj Kumar Neeraj Kumar Neeraj Kumar Neeraj Kumar Neeraj Kumar Neeraj Kumar Neeraj Kumar Neeraj Kumar Neeraj Kumar

While Loop with else

 

The while loop also supports the else statement, which is optional. When working with other statements in Python, the following points must be remembered.

 

  • The else statement will be written after the while statement and executed when the expression of while returns false.
  • If the break statement is executed inside the while loop in Python, the execution will be stopped, and the else statement will be skipped.

 

Syntax

while expression: statement(s) else: Statement(s)

The following program demonstrates while with an else statement.

 

Program

count = 0; while count < 20: print("My name is Harry Potter") count += 1 else: print("String is printed 20 times")

Output

My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter My name is Harry Potter

String is printed 20 times

Single Statement While Loop in Python

If Python has only one statement, it can be placed in the same line as the while header statement. The syntax below makes this clear.

 

while expression: statement

 

If there are multiple statements, it only works for a single statement. All of them should be written inside the body of the while loop.

 

The following program demonstrates the single-line statement.

 

Program

count = 0 while count < 10: print("I run Infinitely") 

Output

I run Infinitely I run Infinitely I run Infinitely I run Infinitely I run Infinitely I run Infinitely I run Infinitely I run Infinitely I run Infinitely I run Infinitely I run Infinitely I run Infinitely

The Infinite While Loop in Python

The infinite loop never stops its repeated execution because the expression or condition defined by the while loop never returns false. There are many uses of the infinite loop in programming. This loop type is very useful in certain situations, such as in programs that need to run continuously, like servers, real-time monitoring systems, and network servers. To manage such loops in Python, it is crucial to include mechanisms for graceful termination, such as break statements or external interrupts.

 

The following program demonstrates the Infinite loop using the game.

 

Program

import random  def guess_number_game(): """ A simple number guessing game where the user guesses a number between 1 and 100 until they get it right. """ number_to_guess = random.randint(1, 100) attempts = 0  print("Welcome to the Number Guessing Game!") print("Guess the number between 1 and 100.")  while True: try: user_guess = int(input("Enter your guess: ")) attempts += 1 if user_guess < number_to_guess: print("Too low! Try again.") elif user_guess > number_to_guess: print("Too high! Try again.") else: print(f"Congratulations! You've guessed the number in {attempts} attempts.") break  except ValueError: print("Invalid input. Please enter a number.")  if __name__ == "__main__": guess_number_game()

Output

Welcome to the Number Guessing Game! Guess the number between 1 and 100. Enter your guess: 5 Too low! Try again. Enter your guess: 80 Too high! Try again. Enter your guess: 70 Too high! Try again. Enter your guess: 65 Too low! Try again. Enter your guess: 69 Congratulations! You've guessed the number in 5 attempts.

While Loop Control Statements in Python

The loop control statement is a set of keywords written inside a while loop that affects the flow of execution and alters the loop’s normal execution. Three statements change the execution of the while loop statement: break, continue, and pass.

break

 

The break statement exits the loop in Python. It is often used to stop the loop when a certain condition is met, or an event requires terminating it.

 

The following program demonstrates the break.

 

Program

count = 0 while True: count += 1 print(count) if count >= 5: break

Output

1 2 3 4 5

The above program runs indefinitely because of the while true condition. However, the count reaches five, the break statement terminates the loop.

continue

 

The continue statement skips the remaining source code inside the loop for the current iterations and proceeds to the next iterations. It is useful when you want to skip over certain conditions and continue processing the next iteration.

 

The following program demonstrates the Program.

 

Program

counter = 0 while counter < 10: if counter % 2 ==0 : counter += 1 continue  print(counter)  counter +=1 

Output

1 3 5 7 9

Pass Statement

The pass statement does nothing in the Python program. It is used when a statement is syntactically required but you do not want to execute any source code. This is very useful when sketching out your program’s structure and if you haven’t yet implemented certain program parts.

The following program demonstrates the Pass Statement.

Program

counter = 0 while counter < 15: if counter % 3 == 0: pass else: print(f"Number not divisible by 3: {counter}"  counter += 1

Output

Number not divisible by 3: 1 Number not divisible by 3: 2 Number not divisible by 3: 4 Number not divisible by 3: 5 Number not divisible by 3: 7 Number not divisible by 3: 8 Number not divisible by 3: 10 Number not divisible by 3: 11 Number not divisible by 3: 13 Number not divisible by 3: 14

Conclusion

In this article, we learned about the Python while loop. It is crucial for effective programming as it allows you to execute code repeatedly based on dynamic conditions. The while loop’s syntax is simple: it consists of the while keyword followed by a condition and a block of source code that runs as long as the condition is true. Whale loops provide a powerful tool for managing iterative processes and adapting to changing conditions, making them an essential component of Python programming.

FAQs
The break statement exits the loop immediately, regardless of the conditions.
No, Python does not have a do-while loop, but you can simulate it using a while loop with a break statement.
Yes,  you can modify variables inside the loop, but ensure it eventually makes the loop’s condition false.

Updated on September 19, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved