Keywords: loops, iterations sets, conditional loops, counting loops, while loop, for loop,
The while loop in Python is used when you want an operation to be repeated as long as a specified condition is met.
The While loop is used to iterate (repeat) part of the program several times. If the number of iterations (repetitions) you want to perform is not fixed, it is recommended to use a While loop. Generally, we can imagine the While loop as a repetition of one or more sequences that occur as long as one or more conditions are met.
The while loop is used to iterate a sequence of operations several times. In other words, you repeat parts of your program several times, thus enabling general and dynamic applications because code is reused any number of times. If the number of iterations not is fixed, it’s recommended to use a while loop.
The flow chart below shows the functions of a while loop
Let’s break it down
In short, the while loop in Python:
While loop in Python:
If we use the elements in the list above and insert in the code editor:
while condition: code executed within the loop
All code indented after the while command will execute if the condition is True
We’ll see a simple example of how we can use the while loop to perform an operation while the specified condition is met.
After that we create our while loop.
i = 0 while i < 5: print(i) i = i +1 # add 1 to the variable i
In this example, we print the value for the variable i as long as the condition is met. In other word, as long as i is less than 5. The program will thus print the value five times and then end the while loop. The result is
0 1 2 3 4
Note, what had happened if i ++ had not been in the loop? Exactly, the condition for the loop will always be fulfilled (zero is always less than five) and the while loop will not end.
Please leave feedback and help us continue to make our site better.
How useful was this article?
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?
A while loop in Java is a so-called condition loop. This means repeating a code sequence, over and over again, until a condition is met. Instead of having to rewrite your code several times, we can instead repeat a code block several times. If the number of iterations not is fixed, it’s recommended to use a while loop.
while condition: code executed within the loop