When the Condition Is True It Will Execute Otherwise It Ask Again Again C++

Welcome! If yous want to learn how to work with while loops in Python, then this article is for yous.
While loops are very powerful programming structures that yous can utilize in your programs to repeat a sequence of statements.
In this article, y'all 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 infinite loops are and how to interrupt them.
- What
while True
is used for and its general syntax. - How to use a
break
statement to stop a while loop.
You volition acquire how while loops work behind the scenes with examples, tables, and diagrams.
Are you ready? Let's begin. 🔅
🔹 Purpose and Utilise Cases for While Loops
Let's starting time with the purpose of while loops. What are they used for?
They are used to echo a sequence of statements an unknown number of times. This type of loop runs while a given condition is Truthful
and information technology simply stops when the status becomes Imitation
.
When we write a while loop, nosotros don't explicitly define how many iterations will be completed, nosotros only write the condition that has to be True
to continue the process and False
to stop it.
💡 Tip: if the while loop status never evaluates to Fake
, then we volition take an infinite loop, which is a loop that never stops (in theory) without external intervention.
These are some examples of real use cases of while loops:
- User Input: When we inquire for user input, we need to check if the value entered is valid. We tin't mayhap know in advance how many times the user will enter an invalid input before the program tin can go on. Therefore, a while loop would be perfect for this scenario.
- Search: searching for an element in a data structure is another perfect use instance for a while loop because nosotros tin can't know in advance how many iterations volition exist needed to find the target value. For instance, the Binary Search algorithm tin be implemented using a while loop.
- Games: In a game, a while loop could be used to go on 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, so this is some other perfect scenario for a while loop.
🔸 How While Loops Work
Now that you know what while loops are used for, permit's see their primary logic and how they work behind the scenes. Here we have a diagram:

Let's break this down in more than detail:
- The process starts when a while loop is found during the execution of the program.
- The condition is evaluated to bank check if information technology's
Truthful
orFalse
. - If the status is
True
, the statements that vest to the loop are executed. - The while loop condition is checked again.
- If the condition evaluates to
True
again, the sequence of statements runs over again and the procedure is repeated. - When the condition evaluates to
False
, the loop stops and the programme continues beyond the loop.
One of the most important characteristics of while loops is that the variables used in the loop condition are non updated automatically. We have to update their values explicitly with our code to brand sure that the loop will eventually finish when the condition evaluates to False
.
🔹 General Syntax of While Loops
Groovy. At present y'all know how while loops work, so allow'southward dive into the code and see how you can write a while loop in Python. This is the basic syntax:

These are the main elements (in order):
- The
while
keyword (followed by a space). - A condition to decide if the loop volition continue running or not based on its truth value (
True
orFaux
). - A colon (
:
) at the end of the starting time line. - The sequence of statements that will be repeated. This block of code is called the "body" of the loop and it has to be indented. If a statement is not indented, information technology volition not be considered role of the loop (please run into the diagram below).

💡 Tip: The Python style guide (PEP eight) recommends using 4 spaces per indentation level. Tabs should simply be used to remain consequent with lawmaking that is already indented with tabs.
🔸 Examples of While Loops
Now that you know how while loops work and how to write them in Python, let's run across how they work backside the scenes with some examples.
How a Basic While Loop Works
Hither we have a basic while loop that prints the value of i
while i
is less than 8 (i < eight
):
i = 4 while i < 8: print(i) i += 1
If we run the code, we see this output:
4 5 6 seven
Permit'southward encounter what happens behind the scenes when the code runs:

- Iteration 1: initially, the value of
i
is 4, so the conditioni < viii
evaluates toTruthful
and the loop starts to run. The value ofi
is printed (iv) and this value is incremented by 1. The loop starts once more. - Iteration 2: now the value of
i
is v, so the conditioni < eight
evaluates toTrue
. The body of the loop runs, the value ofi
is printed (5) and this valuei
is incremented by ane. The loop starts once again. - Iterations 3 and four: The same process is repeated for the third and 4th iterations, then the integers 6 and 7 are printed.
- Earlier starting the fifth iteration, the value of
i
isviii
. Now the while loop statusi < 8
evaluates toFalse
and the loop stops immediately.
💡 Tip: If the while loop status is Simulated
before starting the first iteration, the while loop volition not even start running.
User Input Using a While Loop
At present let's see an example of a while loop in a plan that takes user input. We will the input()
office to ask the user to enter an integer and that integer will only be appended to listing if it's fifty-fifty.
This is the code:
# Ascertain the list nums = [] # The loop will run while the length of the # list nums is less than 4 while len(nums) < 4: # Ask for user input and store it in a variable as an integer. user_input = int(input("Enter an integer: ")) # If the input is an even number, add it to the list if user_input % 2 == 0: nums.suspend(user_input)
The loop condition is len(nums) < four
, so the loop will run while the length of the list nums
is strictly less than 4.
Allow'due south clarify this program line by line:
- We outset by defining an empty list and assigning information technology to a variable chosen
nums
.
nums = []
- And then, nosotros define a while loop that will run while
len(nums) < four
.
while len(nums) < 4:
- Nosotros ask for user input with the
input()
part and store information technology in theuser_input
variable.
user_input = int(input("Enter an integer: "))
💡 Tip: We demand to catechumen (cast) the value entered by the user to an integer using the int()
part before assigning it to the variable because the input()
function returns a cord (source).
- Nosotros check if this value is fifty-fifty or odd.
if user_input % ii == 0:
- If it's fifty-fifty, we append it to the
nums
list.
nums.append(user_input)
- Else, if it'south odd, the loop starts again and the condition is checked to determine if the loop should continue or not.
If we run this code with custom user input, we get the post-obit output:
Enter an integer: 3 Enter an integer: 4 Enter an integer: two Enter an integer: 1 Enter an integer: seven Enter an integer: half dozen Enter an integer: three Enter an integer: 4
This table summarizes what happens behind the scenes when the lawmaking runs:

💡 Tip: The initial value of len(nums)
is 0
because 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 check the condition earlier the next iteration starts.
As you can see in the table, the user enters even integers in the second, third, sixth, and eight iterations and these values are appended to the nums
listing.
Before a "ninth" iteration starts, the status is checked again but at present it evaluates to False
because the nums
list has four elements (length 4), and then the loop stops.
If we check the value of the nums
list when the process has been completed, we run across this:
>>> nums [iv, ii, half-dozen, iv]
Exactly what nosotros expected, the while loop stopped when the status len(nums) < iv
evaluated to Simulated
.
Now you know how while loops piece of work behind the scenes and you've seen some practical examples, and so allow'southward dive into a key element of while loops: the condition.
🔹 Tips for the Condition in While Loops
Before you get-go working with while loops, yous should know that the loop status plays a central office in the functionality and output of a while loop.

You must be very careful with the comparison operator that yous choose 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 tin affect the number of iterations of the loop and even its output.
Let'southward see an example:
If we write this while loop with the condition i < nine
:
i = six while i < nine: print(i) i += ane
We see this output when the code runs:
6 seven viii
The loop completes 3 iterations and information technology stops when i
is equal to 9
.
This table illustrates what happens behind the scenes when the code runs:

- Earlier the first iteration of the loop, the value of
i
is 6, so the conditioni < 9
isTrue
and the loop starts running. The value ofi
is printed and then it is incremented by 1. - In the 2nd iteration of the loop, the value of
i
is 7, so the conditioni < ix
isTrue
. The torso of the loop runs, the value ofi
is printed, and then information technology is incremented by 1. - In the tertiary iteration of the loop, the value of
i
is 8, so the statusi < ix
isTruthful
. The body of the loop runs, the value ofi
is printed, and then it is incremented past 1. - The status is checked again before a quaternary iteration starts, but at present the value of
i
is 9, soi < 9
isFalse
and the loop stops.
In this case, nosotros used <
as the comparison operator in the condition, but what do you think volition happen if we use <=
instead?
i = 6 while i <= nine: impress(i) i += one
We run across this output:
vi vii 8 9
The loop completes 1 more iteration because now we are using the "less than or equal to" operator <=
, then the condition is still True
when i
is equal to nine
.
This tabular array illustrates what happens behind the scenes:

Iv iterations are completed. The condition is checked once more before starting a "5th" iteration. At this bespeak, the value of i
is x
, so the condition i <= ix
is False
and the loop stops.
🔸 Infinite While Loops
Now you know how while loops work, just what do you lot call up will happen if the while loop condition never evaluates to False
?

What are Infinite While Loops?
Call back that while loops don't update variables automatically (we are in charge of doing that explicitly with our code). So there is no guarantee that the loop will stop unless we write the necessary code to make the condition False
at some bespeak during the execution of the loop.
If nosotros don't practice this and the condition always evaluates to True
, so we will accept an infinite loop, which is a while loop that runs indefinitely (in theory).
Space loops are typically the effect of a bug, but they tin can likewise be caused intentionally when nosotros want to echo a sequence of statements indefinitely until a break
statement is establish.
Let's run across these two types of infinite loops in the examples below.
💡 Tip: A bug is an error in the program that causes incorrect or unexpected results.
Example of Infinite Loop
This is an example of an unintentional infinite loop acquired past a problems in the program:
# Define a variable i = five # Run this loop while i is less than xv while i < 15: # Print a bulletin print("Hi, Globe!")
Analyze this code for a moment.
Don't you lot detect something missing in the torso of the loop?
That'southward right!
The value of the variable i
is never updated (it'due south ever 5
). Therefore, the status i < 15
is e'er True
and the loop never stops.
If nosotros run this lawmaking, the output will be an "infinite" sequence of Howdy, World!
messages because the body of the loop print("Hello, World!")
volition run indefinitely.
Hello, Earth! Hello, World! Hullo, World! Hi, World! Howdy, World! Hello, Earth! Hello, Globe! How-do-you-do, World! Hi, Globe! Howdy, World! Hello, World! Howdy, World! Hello, World! Hi, Globe! Hello, World! Hello, World! How-do-you-do, World! Hello, World! . . . # Continues indefinitely
To stop the programme, we will need to interrupt the loop manually by pressing CTRL + C
.
When we practice, nosotros will see a KeyboardInterrupt
fault similar to this one:

To gear up this loop, nosotros will need to update the value of i
in the body of the loop to make sure that the condition i < 15
will somewhen evaluate to Fake
.
This is one possible solution, incrementing the value of i
past ii on every iteration:
i = 5 while i < 15: print("Howdy, World!") # Update the value of i i += 2
Not bad. Now yous know how to ready infinite loops acquired past a bug. You just need to write code to guarantee that the condition volition somewhen evaluate to Simulated
.
Allow's start diving into intentional infinite loops and how they piece of work.
🔹 How to Brand an Infinite Loop with While True
Nosotros can generate an space loop intentionally using while True
. In this example, the loop volition run indefinitely until the process is stopped by external intervention (CTRL + C
) or when a intermission
statement is found (yous volition learn more about break
in only a moment).
This is the basic syntax:

Instead of writing a status afterward the while
keyword, we but write the truth value directly to indicate that the condition will ever be True
.
Here we accept an example:
>>> while True: print(0) 0 0 0 0 0 0 0 0 0 0 0 0 0 Traceback (most recent call terminal): File "<pyshell#2>", line 2, in <module> print(0) KeyboardInterrupt
The loop runs until CTRL + C
is pressed, but Python too has a break
statement that we can utilise directly in our code to stop this blazon of loop.
The intermission
statement
This statement is used to stop a loop immediately. You should think of it as a scarlet "stop sign" that you tin use in your code to have more command over the behavior of the loop.

According to the Python Documentation:
Theintermission
statement, like in C, breaks out of the innermost enclosingfor
orwhile
loop.
This diagram illustrates the basic logic of the break
statement:

break
statement This is the basic logic of the interruption
statement:
- The while loop starts just if the status evaluates to
True
. - If a
break
statement is found at any betoken during the execution of the loop, the loop stops immediately. - Else, if
break
is non plant, the loop continues its normal execution and it stops when the condition evaluates toFalse
.
We can use intermission
to stop a while loop when a condition is met at a detail signal of its execution, so y'all will typically detect it within a conditional statement, similar this:
while True: # Lawmaking if <condition>: break # Code
This stops the loop immediately if the condition is Truthful
.
💡 Tip: You lot can (in theory) write a pause
statement anywhere in the trunk of the loop. It doesn't necessarily have to be part of a conditional, merely we unremarkably use information technology to stop the loop when a given condition is True
.
Here we have an case of pause
in a while True
loop:

Let's run across it in more than detail:
The first line defines a while Truthful
loop that will run indefinitely until a break
statement is found (or until information technology is interrupted with CTRL + C
).
while True:
The 2nd 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 tertiary line checks if the input is odd.
if user_input % 2 != 0:
If it is, the message This number is odd
is printed and the break
statement stops the loop immediately.
print("This number of odd") break
Else, if the input is even , the message This number is even
is printed and the loop starts again.
print("This number is even")
The loop will run indefinitely until an odd integer is entered because that is the but style in which the break
statement volition be constitute.
Here we have an instance with custom user input:
Enter an integer: 4 This number is even Enter an integer: 6 This number is even Enter an integer: 8 This number is even Enter an integer: iii This number is odd >>>
🔸 In Summary
- While loops are programming structures used to echo a sequence of statements while a status is
True
. They stop when the status evaluates toFalse
. - When you write a while loop, yous need to make the necessary updates in your code to make sure that the loop will somewhen stop.
- An space loop is a loop that runs indefinitely and it only stops with external intervention or when a
break
statement is found. - Yous can stop an infinite loop with
CTRL + C
. - Y'all tin can generate an infinite loop intentionally with
while Truthful
. - The
suspension
argument tin be used to end a while loop immediately.
I really hope you liked my commodity and found it helpful. Now y'all know how to work with While Loops in Python.
Follow me on Twitter @EstefaniaCassN and if you desire to learn more about this topic, check out my online course Python Loops and Looping Techniques: Beginner to Advanced.
Acquire to lawmaking for free. freeCodeCamp's open source curriculum has helped more than twoscore,000 people become jobs as developers. Become started
Source: https://www.freecodecamp.org/news/python-while-loop-tutorial/
Post a Comment for "When the Condition Is True It Will Execute Otherwise It Ask Again Again C++"