Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Itertools.takewhile()
Next article icon

Python While Loop

Last Updated : 10 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.

In this example, the condition for while will be True as long as the counter variable (count) is less than 3. 

Python
# Python example for while loop count = 0 while (count < 3):     count = count + 1     print("Hello Geek") 

Output
Hello Geek Hello Geek Hello Geek 

Let’s take a look at Python While Loop in detail:

Table of Content

  • Infinite while Loop in Python
  • while loop with continue statement
  • while loop with break statement
  • while loop with pass statement
  • while loop with else

while loop Syntax

while expression:
statement(s)

  • condition: This is a boolean expression. If it evaluates to True, the code inside the loop will execute.
  • statement(s): These are the statements that will be executed during each iteration of the loop.

While Loop Flowchart

Python While Loop

While Loop

The while loop will continue running the code block as long as the condition evaluates to True. Each time the loop executes, the condition is checked again. If it is True, the loop continues; if it is False, the loop terminates, and the program moves to the next statement after the loop.

Infinite while Loop in Python

Here, the value of the condition is always True. Therefore, the body of the loop is run infinite times until the memory is full.

Python
age = 28  # the test condition is always True while age > 19:     print('Infinite Loop') 

Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.

while loop with continue statement

Python Continue Statement returns the control to the beginning of the loop.

Python
# Prints all letters except 'e' and 's' i = 0 a = 'geeksforgeeks'  while i < len(a):     if a[i] == 'e' or a[i] == 's':         i += 1         continue              print(a[i])     i += 1 

Output
g k f o r g k 

while loop with break statement

Python Break Statement brings control out of the loop.

Python
# break the loop as soon it sees 'e' # or 's' i = 0 a = 'geeksforgeeks'  while i < len(a):     if a[i] == 'e' or a[i] == 's':         i += 1         break              print(a[i])     i += 1 

Output
g 

while loop with pass statement

The Python pass statement to write empty loops. Pass is also used for empty control statements, functions, and classes.

Python
# An empty loop a = 'geeksforgeeks' i = 0  while i < len(a):     i += 1     pass    print('Value of i :', i) 

Output
Value of i : 13 

while loop with else

As discussed above, while loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed. The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.

Note: The else block just after for/while is executed only when the loop is NOT terminated by a break statement. 

Python
# Python program to demonstrate # while-else loop  i = 0 while i < 4:     i += 1     print(i) else:  # Executed because no break in for     print("No Break\n")  i = 0 while i < 4:     i += 1     print(i)     break else:  # Not executed as there is a break     print("No Break") 

Output
1 2 3 4 No Break  1 


Next Article
Python - Itertools.takewhile()

N

nikhilaggarwal3
Improve
Article Tags :
  • Python
  • python
  • Python loop-programs
  • python-basics
Practice Tags :
  • python
  • python

Similar Reads

  • Python Do While Loops
    In Python, there is no construct defined for do while loop. Python loops only include for loop and while loop but we can modify the while loop to work as do while as in any other languages such as C++ and Java. In Python, we can simulate the behavior of a do-while loop using a while loop with a cond
    6 min read
  • Python While Else
    Python is easy to understand and a robust programming language that comes with lots of features. It offers various control flow statements that are slightly different from those in other programming languages. The "while-else" loop is one of these unique constructs. In this article, we will discuss
    6 min read
  • Python - Itertools.takewhile()
    The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easy. One such itertools function is takewhile(). Note: For more information, refer to Python Itertools takewhile() This al
    3 min read
  • Decrement in While Loop in Python
    A loop is an iterative control structure capable of directing the flow of the program based on the authenticity of a condition. Such structures are required for the automation of tasks. There are 2 types of loops presenting the Python programming language, which are: for loopwhile loop This article
    3 min read
  • Looping Techniques in Python
    Python supports various looping techniques by certain inbuilt functions, in various sequential containers. These methods are primarily very useful in competitive programming and also in various projects that require a specific technique with loops maintaining the overall structure of code. A lot of
    6 min read
  • Python Else Loop
    Else with loop is used with both while and for loop. The else block is executed at the end of loop means when the given loop condition is false then the else block is executed. So let's see the example of while loop and for loop with else below. Else with While loop Consider the below example. C/C++
    3 min read
  • Python: Map VS For Loop
    Map in Python : Map is used to compute a function for different values 'in a single line of code ' . It takes two arguments, first is function name, that is defined already and the other is list, tuple or any other iterables . It is a way of applying same function for multiple numbers . It generates
    3 min read
  • Python Nested Loops
    In Python programming language there are two types of loops which are for loop and while loop. Using these loops we can create nested loops in Python. Nested loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside the for loop, etc. Python Nested Loops Syntax:Out
    9 min read
  • Python Variables
    In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
    7 min read
  • Python - Loop Through a Range
    Looping through a range is an important operation in Python. In this article, we will explore the different ways to loop through a range in Python, demonstrating how we customize start, end, and step values, as well as alternative methods for more advanced use cases like looping through floating-poi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences