Python is an object-oriented programming language that is used for application development, web development, and data analytics. Python is the most popular programming language right now partly because it’s free and open-source, has a vast standard library, and can be easily integrated with other programming languages. Among other components, Python consists of three main types of loops:
- While loops
- For loops
- Nested loops
This article covers Python programming's fundamental looping statements, i.e., Python while loops. We’ll provide an overview of Python while loops, including break statements, continue statements, and while loops with else—closing with a Python while loop exercise.
What Is Python While Loop?
A While loop is used to repeat a section of code an unknown number of times until a specific condition is met.
Shown below is the syntax of a Python while loop.
Syntax: WHILE EXPRESSION:
Fig: Operation of Python while loop
Fig: Python While loop
For the above program, we assigned a value to the variable x as 1. While the value of the x is less than 5, it is going to print the value of x; after each iteration, the value of x will be increased by 1.
Break Statement in While Loop
The Python break statement is used to exit from the loop immediately after a particular condition is met.
Fig: Break statement
In the above statement, the while loop executes until x becomes 3. As soon as the value of x becomes equal to 3, the loop breaks.
Continue Statement in While Loop
The function of the continue statement is to skip the current iteration of a loop and continue with the next one.
Fig: Continue statement
The following loop goes until the x=3. When x becomes 3, the current iteration stops and a new iteration starts.
While Loop With Else
Python allows an else clause at the end of a while loop. The else part is executed if the loop terminates naturally.
Fig: While loop with else
The following code executes as follows. We assign the value to variable x=1. Till x is less than 5, the loop will continue and print the value. As soon as the value of x reaches 4, the else condition is executed.
Python While Loop Exercise
We would suggest attempting the following question on your own before you refer to the solutions.
Question: Write a program to add all the numbers less than 10 using while loop.
Fig: Solution 1
Learn data operations in Python, strings, conditional statements, error handling, and the commonly used Python web framework Django. Check out Simplilearn's Python Training course.
Learn Python and Take Your Career to the Next Level
Understanding Python loops is one of the many steps toward mastering this exciting and versatile programming language. As big data and business intelligence become more broadly adopted across all industries, mastering Python could open doors in your professional career. Simplilearn’s Python Training Course is a great introduction to this dynamic programming language.