If Yes Is Entered Run the Program Again
Welcome! If you want to learn how to work with while loops in Python, then this article is for you.
While loops are very powerful programming structures that you tin use in your programs to echo a sequence of statements.
In this article, yous will larn:
- What while loops are.
- What they are used for.
- When they should be used.
- How they work behind the scenes.
- How to write a while loop in Python.
- What space loops are and how to interrupt them.
- What
while Trueis used for and its general syntax. - How to use a
breakstatement to cease a while loop.
You will learn how while loops work backside the scenes with examples, tables, and diagrams.
Are you ready? Let's brainstorm. 🔅
🔹 Purpose and Use Cases for While Loops
Let's start with the purpose of while loops. What are they used for?
They are used to repeat a sequence of statements an unknown number of times. This blazon of loop runs while a given condition is Truthful and it merely stops when the condition becomes False.
When we write a while loop, we don't explicitly define how many iterations will be completed, we simply write the status that has to exist True to continue the procedure and False to stop information technology.
💡 Tip: if the while loop status never evaluates to False, and so we will accept an space loop, which is a loop that never stops (in theory) without external intervention.
These are some examples of existent use cases of while loops:
- User Input: When we ask for user input, we demand to check if the value entered is valid. We can't possibly know in accelerate how many times the user will enter an invalid input earlier the program tin continue. Therefore, a while loop would be perfect for this scenario.
- Search: searching for an element in a data structure is another perfect use case for a while loop because we can't know in accelerate how many iterations volition be needed to find the target value. For instance, the Binary Search algorithm can exist implemented using a while loop.
- Games: In a game, a while loop could exist used to proceed the main logic of the game running until the player loses or the game ends. We can't know in advance when this will happen, then this is another perfect scenario for a while loop.
🔸 How While Loops Work
Now that you know what while loops are used for, allow's see their principal logic and how they work behind the scenes. Here we have a diagram:
Let'southward break this down in more detail:
- The process starts when a while loop is institute during the execution of the program.
- The condition is evaluated to check if it'due south
TrueorFalse. - If the condition is
True, the statements that belong to the loop are executed. - The while loop condition is checked again.
- If the condition evaluates to
Truthfulagain, the sequence of statements runs again and the process is repeated. - When the condition evaluates to
False, the loop stops and the program continues beyond the loop.
One of the most important characteristics of while loops is that the variables used in the loop condition are not updated automatically. We accept to update their values explicitly with our code to make sure that the loop will eventually stop when the condition evaluates to Simulated.
🔹 General Syntax of While Loops
Neat. At present yous know how while loops work, so let'due south dive into the lawmaking and see how you can write a while loop in Python. This is the basic syntax:
These are the chief elements (in order):
- The
whilekeyword (followed past a space). - A status to determine if the loop will go along running or not based on its truth value (
TruthfulorSimulated). - A colon (
:) at the end of the showtime line. - The sequence of statements that will be repeated. This block of code is chosen the "body" of the loop and it has to be indented. If a statement is not indented, it will not be considered part of the loop (delight see the diagram below).
💡 Tip: The Python style guide (PEP viii) recommends using 4 spaces per indentation level. Tabs should only be used to remain consistent with code that is already indented with tabs.
🔸 Examples of While Loops
Now that you know how while loops piece of work and how to write them in Python, let's come across how they work behind the scenes with some examples.
How a Basic While Loop Works
Here nosotros have a basic while loop that prints the value of i while i is less than 8 (i < viii):
i = 4 while i < 8: impress(i) i += one If nosotros run the code, we encounter this output:
4 v 6 seven Permit's see what happens backside the scenes when the code runs:
- Iteration 1: initially, the value of
iis 4, and then the conditioni < 8evaluates toTrueand the loop starts to run. The value ofiis printed (4) and this value is incremented by 1. The loop starts again. - Iteration 2: now the value of
iis five, then the conditioni < viiievaluates toTrue. The body of the loop runs, the value ofiis printed (5) and this valueiis incremented by 1. The loop starts over again. - Iterations three and 4: The same process is repeated for the 3rd and fourth iterations, and so the integers vi and 7 are printed.
- Earlier starting the fifth iteration, the value of
iis8. Now the while loop conditioni < 8evaluates toFalseand the loop stops immediately.
💡 Tip: If the while loop condition is False before starting the first iteration, the while loop will not even start running.
User Input Using a While Loop
Now let'south meet an example of a while loop in a program that takes user input. We will the input() function to inquire the user to enter an integer and that integer will simply be appended to list if information technology'due south even.
This is the lawmaking:
# Ascertain the listing nums = [] # The loop volition run while the length of the # list nums is less than 4 while len(nums) < 4: # Ask for user input and store information technology in a variable every bit an integer. user_input = int(input("Enter an integer: ")) # If the input is an even number, add together information technology to the list if user_input % two == 0: nums.append(user_input) The loop condition is len(nums) < 4, so the loop volition run while the length of the listing nums is strictly less than four.
Let'southward clarify this plan line by line:
- We start by defining an empty list and assigning it to a variable called
nums.
nums = [] - Then, we define a while loop that will run while
len(nums) < 4.
while len(nums) < iv: - We enquire for user input with the
input()office and store it in theuser_inputvariable.
user_input = int(input("Enter an integer: ")) 💡 Tip: We demand to catechumen (bandage) the value entered past the user to an integer using the int() function before assigning it to the variable because the input() role returns a string (source).
- We check if this value is even or odd.
if user_input % 2 == 0: - If it's even, we append it to the
numslisting.
nums.suspend(user_input) - Else, if information technology'due south odd, the loop starts again and the status is checked to determine if the loop should continue or not.
If we run this code with custom user input, we get the following output:
Enter an integer: 3 Enter an integer: 4 Enter an integer: two Enter an integer: 1 Enter an integer: vii Enter an integer: 6 Enter an integer: 3 Enter an integer: 4 This table summarizes what happens behind the scenes when the code runs:
💡 Tip: The initial value of len(nums) is 0 considering the list is initially empty. The final cavalcade of the table shows the length of the list at the end of the current iteration. This value is used to bank check the status before the next iteration starts.
As you lot can meet in the tabular array, the user enters even integers in the second, third, sixth, and eight iterations and these values are appended to the nums list.
Before a "ninth" iteration starts, the condition is checked over again but now it evaluates to False because the nums list has four elements (length 4), so the loop stops.
If we check the value of the nums list when the procedure has been completed, nosotros see this:
>>> nums [iv, 2, 6, iv] Exactly what we expected, the while loop stopped when the status len(nums) < 4 evaluated to False.
Now you know how while loops work behind the scenes and you lot've seen some practical examples, then let's dive into a primal element of while loops: the status.
🔹 Tips for the Condition in While Loops
Before y'all start working with while loops, you should know that the loop condition plays a central role in the functionality and output of a while loop.
Yous must exist very conscientious with the comparison operator that you cull because this is a very common source of bugs.
For example, common errors include:
- Using
<(less than) instead of<=(less than or equal to) (or vice versa). - Using
>(greater than) instead of>=(greater than or equal to) (or vice versa).
This can affect the number of iterations of the loop and even its output.
Let'south come across an example:
If we write this while loop with the condition i < 9:
i = half-dozen while i < 9: print(i) i += 1 We see this output when the lawmaking runs:
vi 7 8 The loop completes iii iterations and it stops when i is equal to 9.
This tabular array illustrates what happens behind the scenes when the lawmaking runs:
- Before the first iteration of the loop, the value of
iis half-dozen, so the conditioni < nineisTrueand the loop starts running. The value ofiis printed and so it is incremented past 1. - In the second iteration of the loop, the value of
iis 7, so the conditioni < 9isTrue. The body of the loop runs, the value ofiis printed, and then it is incremented by 1. - In the 3rd iteration of the loop, the value of
iis 8, and then the conditioni < 9isTrue. The body of the loop runs, the value ofiis printed, and then it is incremented by 1. - The condition is checked again earlier a fourth iteration starts, but at present the value of
iis 9, theni < 9isFalseand the loop stops.
In this case, nosotros used < as the comparison operator in the condition, but what exercise yous recollect will happen if nosotros use <= instead?
i = 6 while i <= 9: print(i) i += i We see this output:
6 seven 8 nine The loop completes one more iteration because at present nosotros are using the "less than or equal to" operator <= , so the status is yet True when i is equal to nine.
This table illustrates what happens behind the scenes:
Four iterations are completed. The condition is checked once more earlier starting a "5th" iteration. At this signal, the value of i is 10, so the condition i <= nine is False and the loop stops.
🔸 Infinite While Loops
Now you know how while loops work, just what do you retrieve will happen if the while loop condition never evaluates to False?
What are Infinite While Loops?
Recollect that while loops don't update variables automatically (we are in charge of doing that explicitly with our code). So at that place is no guarantee that the loop will cease unless we write the necessary code to make the condition False at some bespeak during the execution of the loop.
If we don't practice this and the condition e'er evaluates to Truthful, then nosotros will have an space loop, which is a while loop that runs indefinitely (in theory).
Infinite loops are typically the issue of a bug, only they tin can too be caused intentionally when we want to repeat a sequence of statements indefinitely until a break statement is found.
Let's encounter these two types of infinite loops in the examples beneath.
💡 Tip: A problems is an mistake in the programme that causes incorrect or unexpected results.
Case of Infinite Loop
This is an instance of an unintentional space loop caused past a bug in the programme:
# Define a variable i = 5 # Run this loop while i is less than 15 while i < 15: # Print a message impress("Hello, Earth!") Analyze this code for a moment.
Don't y'all notice something missing in the trunk of the loop?
That'south correct!
The value of the variable i is never updated (it's e'er 5). Therefore, the condition i < 15 is always True and the loop never stops.
If we run this code, the output will be an "infinite" sequence of Hullo, Globe! messages considering the body of the loop print("Hello, World!") volition run indefinitely.
Hello, World! Hello, Earth! Hello, World! Hello, Earth! Howdy, World! Howdy, World! Hello, Earth! How-do-you-do, Globe! How-do-you-do, Earth! How-do-you-do, Earth! Hullo, Globe! Hello, World! Hello, Globe! Hullo, Earth! Hello, World! Hello, Globe! How-do-you-do, World! How-do-you-do, Earth! . . . # Continues indefinitely To stop the program, we will need to interrupt the loop manually by pressing CTRL + C.
When we do, we will see a KeyboardInterrupt fault similar to this 1:
To set this loop, we volition need to update the value of i in the torso of the loop to make sure that the condition i < 15 volition eventually evaluate to False.
This is i possible solution, incrementing the value of i by two on every iteration:
i = 5 while i < xv: print("How-do-you-do, World!") # Update the value of i i += 2 Corking. Now you know how to fix space loops caused past a bug. You just demand to write code to guarantee that the condition will eventually evaluate to Simulated.
Let's start diving into intentional infinite loops and how they work.
🔹 How to Make an Infinite Loop with While True
Nosotros can generate an space loop intentionally using while Truthful. In this case, the loop will run indefinitely until the process is stopped by external intervention (CTRL + C) or when a break statement is institute (you will learn more virtually break in just a moment).
This is the basic syntax:
Instead of writing a condition after the while keyword, we only write the truth value directly to betoken that the condition will always be True.
Here we have an case:
>>> while True: print(0) 0 0 0 0 0 0 0 0 0 0 0 0 0 Traceback (well-nigh recent call last): File "<pyshell#two>", line 2, in <module> impress(0) KeyboardInterrupt The loop runs until CTRL + C is pressed, but Python also has a intermission statement that we tin can use directly in our code to stop this type of loop.
The break statement
This statement is used to finish a loop immediately. Y'all should think of information technology every bit a red "stop sign" that you lot can utilise in your code to accept more control over the behavior of the loop.
According to the Python Documentation:
Thebreakargument, like in C, breaks out of the innermost enclosingfororwhileloop.
This diagram illustrates the basic logic of the suspension statement:
break statement This is the bones logic of the break statement:
- The while loop starts only if the status evaluates to
True. - If a
suspensionstatement is found at any point during the execution of the loop, the loop stops immediately. - Else, if
breakis not found, the loop continues its normal execution and it stops when the condition evaluates toFalse.
We can use break to stop a while loop when a status is met at a particular betoken of its execution, so you will typically find it inside a conditional statement, like this:
while True: # Code if <status>: break # Code This stops the loop immediately if the condition is True.
💡 Tip: Y'all can (in theory) write a break statement anywhere in the body of the loop. It doesn't necessarily accept to be part of a conditional, but we commonly use information technology to end the loop when a given condition is Truthful.
Hither we accept an instance of break in a while True loop:
Permit's run into it in more than detail:
The start line defines a while True loop that will run indefinitely until a break statement is establish (or until it is interrupted with CTRL + C).
while True: The 2d line asks for user input. This input is converted to an integer and assigned to the variable user_input.
user_input = int(input("Enter an integer: ")) The 3rd line checks if the input is odd.
if user_input % 2 != 0: If it is, the bulletin This number is odd is printed and the break statement stops the loop immediately.
print("This number of odd") interruption Else, if the input is even , the bulletin This number is even is printed and the loop starts once more.
impress("This number is fifty-fifty") The loop will run indefinitely until an odd integer is entered because that is the simply way in which the break statement will exist constitute.
Here nosotros take an example with custom user input:
Enter an integer: 4 This number is fifty-fifty Enter an integer: vi This number is even Enter an integer: 8 This number is even Enter an integer: 3 This number is odd >>> 🔸 In Summary
- While loops are programming structures used to repeat a sequence of statements while a condition is
True. They stop when the status evaluates toFake. - When you write a while loop, you lot need to make the necessary updates in your code to make sure that the loop will eventually stop.
- An infinite loop is a loop that runs indefinitely and information technology only stops with external intervention or when a
pauseargument is found. - You lot tin stop an infinite loop with
CTRL + C. - You lot can generate an infinite loop intentionally with
while True. - The
breakstatement can exist used to stop a while loop immediately.
I really promise you liked my article and found it helpful. At present you lot know how to work with While Loops in Python.
Follow me on Twitter @EstefaniaCassN and if you want to learn more about this topic, check out my online form Python Loops and Looping Techniques: Beginner to Advanced.
Learn to code for free. freeCodeCamp's open source curriculum has helped more than twoscore,000 people go jobs as developers. Get started
Source: https://www.freecodecamp.org/news/python-while-loop-tutorial/
0 Response to "If Yes Is Entered Run the Program Again"
Post a Comment