Don't Get Stuck: Mastering Python's While Loops
A simple guide to understand how the while loops work in Python
What is a while loop:
A while loop is a conditional loop in python that's used to execute a code block for as long as the boolean condition remains True. This means, as long as the specified condition is True, the while loop will continue iterating and executing the code or rather the task in the code block. This loop is actually used when you have no idea of the number of iterations that you are going to use in a Python loop. A while loop works by evaluating a condition at the start of each iteration. If the condition is true, then the loop executes. Otherwise, it terminates.
What is the Basic Syntax for while loop
while condition :
#code to be executed as long as the condition is TrueFrom the basic syntax you can understand the fact that the while loop is used such that it will evaluate the boolean condition and if it is True, then the code is executed and keeps executing the code block until as such that the condition is no longer True and becomes False.
How To Control the While Loop
You can control the look by using the build-in keywords, break and continue.
The break Statement: The Program exits the loop immediately, skipping any remaining code in the block and the else clause. From the term break, you know, it will help you in ending the loop, whatever be the condition used in the code!
The continue Statement: From the term continue, you know, it skips the current iteration and jumps back to the top to check the condition.
In the later posts, I have included detailed description with examples to explain this behaviour.
When Should You Opt For Using a While Loop
When You Are Unsure about the Number of Iterations: You can use this loop when you are not sure about the number of times the loop needs to iterate.
When You Need a User Input validation: You can use this loop in use cases when you need a User Input Validation whereby you repeat a prompt until the time when the user responds by entering a valid data. For example, consider the prompt, “Enter a name that is for a baby girl starting with the letter ‘M’ and ending with the letter ‘O’.”
For such prompt based programs, you need to use the while loop.
When You Need To Run A Program with an Event based Execution: These are scenarios when you want to run a program continuously until a specific event occurs, for example, consider a program where the user is entering some information and keeps on doing so until the user clicks the ‘Quit’ or ‘Cancel’ button. If the user does not click the cancel button, he can keep on entering the information ! In such programs, you need to use the while loop as it can iterate until the condition is no longer True. In this case the condition is broken with clicking of the quit button.
When You Need To Use Infinite Loops: You can use the While True Loop: This is usually in situations where the user is playing a game with the computer on a server and can keep on playing infinitely until the game loop is terminated using a break statement.
What Are Some Best Practices To Consider
Always Avoid Infinite Loops: You must make sure that the loop does not run infinitely and to provide a logic that will eventually render the condition from True to False so that ultimately, the loop will stop! For example if you are creating a while loop for a counter to keep incrementing a number by 2 every time, make sure that you also are able to provide a condition for example sake, this incrementing needs to stop when the value of the number reaches the value of 100.
Check the Indentation: Be wary of checking the indentation of the code block that is within the loop! Ensure that it is consistent and not changing every time.
What Are the Important Rules For Writing loops:
Initialization: Ensure that you define the variable that you are using in the function before the loop is started.
Indentation: You need to use spaces or tabs to define the code that belongs inside your while loop of the program.
Logic for Updating the Loop Condition : Remember to include an update inside the program in order to make the condition become False later on so that the loop does not run infinitely! For example if you have a loop for creating a counter for incrementing a number, you should have a condition inside the program , such as count += 2 so later on in the program when you have a result that is not adhering to this count update, then, the system will render the condition to False and terminate the loop. For example, [1,3,5,7,8] Here you can see how the result shows that the number after 7 is not following the update of incrementing by 2.
What Are Some Mistakes To Be Avoided When Using While Loops
If you forgot the condition that you are testing in a while loop, you will end up with an infinite loop!
If you get the start or end conditions wrong, you are done for !Imagine having a loop with a counter to end the loop with the condition of number greater than 100. In such a situation, the loop will go on and on !
If you jump out of a loop too early before the condition is fulfilled, by using return statement(s) inside of the loop.Using a return inside the while loop is not advisable since return() is a reserved keyword applicable to be used inside a function and while loop is not a function.
To dive deeper into the intricacies of the while loop, I would invite you to read the How To Use the While Loops in Python.



