How to Have a While Loop Ask a Question Again Python
Welcome! If y'all want to acquire how to work with while loops in Python, then this commodity is for you.
While loops are very powerful programming structures that you lot tin utilise in your programs to repeat a sequence of statements.
In this article, you will learn:
- What while loops are.
- What they are used for.
- When they should exist 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
suspension
statement to cease a while loop.
Yous will larn how while loops work behind the scenes with examples, tables, and diagrams.
Are you ready? Let's begin. 🔅
🔹 Purpose and Use Cases for While Loops
Let'due south kickoff 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 status is Truthful
and it only stops when the condition becomes Faux
.
When we write a while loop, we don't explicitly define how many iterations volition be completed, we only write the condition that has to be True
to go along the process and False
to cease it.
💡 Tip: if the while loop condition never evaluates to False
, then we will accept an space 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 nosotros ask for user input, we demand to check if the value entered is valid. We tin't possibly know in accelerate how many times the user will enter an invalid input before the program tin can proceed. Therefore, a while loop would be perfect for this scenario.
- Search: searching for an chemical element in a data structure is another perfect use case for a while loop because nosotros can't know in advance how many iterations will be needed to find the target value. For example, the Binary Search algorithm can be implemented using a while loop.
- Games: In a game, a while loop could be used to continue 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 another perfect scenario for a while loop.
🔸 How While Loops Work
Now that yous know what while loops are used for, let'south see their main logic and how they work backside the scenes. Here nosotros have a diagram:
Let'due south pause this downwards in more than detail:
- The process starts when a while loop is found during the execution of the plan.
- The condition is evaluated to cheque if it'south
Truthful
orFaux
. - If the condition is
True
, the statements that vest to the loop are executed. - The while loop condition is checked over again.
- If the condition evaluates to
True
again, the sequence of statements runs again and the process is repeated. - When the condition evaluates to
Fake
, 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 status are not updated automatically. We accept to update their values explicitly with our lawmaking to make sure that the loop will eventually stop when the condition evaluates to Faux
.
🔹 Full general Syntax of While Loops
Great. At present yous know how while loops work, so let'south dive into the code and see how you tin 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 status to decide if the loop volition continue running or non based on its truth value (
True
orFalse
). - A colon (
:
) at the cease of the offset line. - The sequence of statements that will be repeated. This cake of code is called the "body" of the loop and information technology has to be indented. If a statement is not indented, it volition non exist considered function of the loop (please see the diagram beneath).
💡 Tip: The Python manner guide (PEP 8) recommends using iv spaces per indentation level. Tabs should merely be used to remain consistent with lawmaking 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 see 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 = iv while i < viii: print(i) i += ane
If we run the code, we see this output:
4 5 6 vii
Permit'southward see what happens behind the scenes when the code runs:
- Iteration 1: initially, the value of
i
is iv, and so the conditioni < 8
evaluates toTrue
and the loop starts to run. The value ofi
is printed (4) and this value is incremented past 1. The loop starts over again. - Iteration ii: at present the value of
i
is 5, so the statusi < 8
evaluates toTrue
. The body of the loop runs, the value ofi
is printed (5) and this valuei
is incremented by 1. The loop starts again. - Iterations 3 and four: The aforementioned process is repeated for the third and fourth iterations, then the integers 6 and 7 are printed.
- Earlier starting the fifth iteration, the value of
i
is8
. Now the while loop conditioni < 8
evaluates toFalse
and the loop stops immediately.
💡 Tip: If the while loop condition is False
earlier starting the beginning iteration, the while loop volition not fifty-fifty start running.
User Input Using a While Loop
At present let'due south see an instance of a while loop in a program that takes user input. We will the input()
part to ask the user to enter an integer and that integer will only be appended to list if it's even.
This is the code:
# Ascertain the list nums = [] # The loop will run while the length of the # listing nums is less than iv while len(nums) < 4: # Ask for user input and shop it in a variable as an integer. user_input = int(input("Enter an integer: ")) # If the input is an fifty-fifty number, add it to the list if user_input % 2 == 0: nums.suspend(user_input)
The loop condition is len(nums) < iv
, and so the loop volition run while the length of the list nums
is strictly less than 4.
Allow's analyze this program line by line:
- We kickoff by defining an empty list and assigning it to a variable chosen
nums
.
nums = []
- Then, we define a while loop that will run while
len(nums) < four
.
while len(nums) < 4:
- We inquire for user input with the
input()
function and store it in theuser_input
variable.
user_input = int(input("Enter an integer: "))
💡 Tip: We need to convert (cast) the value entered by the user to an integer using the int()
function before assigning it to the variable because the input()
office returns a string (source).
- We check if this value is even or odd.
if user_input % 2 == 0:
- If it'south even, we append it to the
nums
list.
nums.suspend(user_input)
- Else, if information technology's odd, the loop starts again and the status is checked to determine if the loop should go on or not.
If we run this code with custom user input, we go the following output:
Enter an integer: 3 Enter an integer: 4 Enter an integer: two Enter an integer: 1 Enter an integer: 7 Enter an integer: vi Enter an integer: 3 Enter an integer: 4
This table summarizes what happens backside the scenes when the code runs:
💡 Tip: The initial value of len(nums)
is 0
because the listing is initially empty. The last cavalcade of the table shows the length of the listing 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, 3rd, sixth, and viii iterations and these values are appended to the nums
list.
Before a "ninth" iteration starts, the condition is checked again merely now it evaluates to Simulated
because the nums
list has four elements (length four), so the loop stops.
If nosotros check the value of the nums
listing when the process has been completed, we see this:
>>> nums [four, 2, six, four]
Exactly what we expected, the while loop stopped when the condition len(nums) < iv
evaluated to False
.
Now you know how while loops work behind the scenes and yous've seen some applied examples, and so let'due south dive into a cardinal element of while loops: the condition.
🔹 Tips for the Condition in While Loops
Before you start working with while loops, y'all should know that the loop condition plays a primal role in the functionality and output of a while loop.
You lot must be very conscientious with the comparison operator that you choose because this is a very common source of bugs.
For example, mutual 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 can affect the number of iterations of the loop and even its output.
Let's encounter an example:
If we write this while loop with the condition i < 9
:
i = vi while i < 9: print(i) i += 1
We run across this output when the code runs:
6 seven 8
The loop completes three iterations and it stops when i
is equal to ix
.
This table illustrates what happens behind the scenes when the lawmaking runs:
- Before the kickoff iteration of the loop, the value of
i
is 6, so the conditioni < 9
isTruthful
and the loop starts running. The value ofi
is printed and then it is incremented by one. - In the 2nd iteration of the loop, the value of
i
is 7, so the conditioni < 9
isTrue
. The body of the loop runs, the value ofi
is printed, and so it is incremented by 1. - In the third iteration of the loop, the value of
i
is 8, then the statusi < ix
isTruthful
. The body of the loop runs, the value ofi
is printed, and so information technology is incremented by 1. - The condition is checked again before a fourth iteration starts, but at present the value of
i
is ix, soi < ix
isFake
and the loop stops.
In this case, nosotros used <
as the comparison operator in the status, only what practice y'all think will happen if nosotros employ <=
instead?
i = 6 while i <= 9: print(i) i += one
We see this output:
half-dozen seven 8 9
The loop completes ane more iteration because now we are using the "less than or equal to" operator <=
, so the status is nonetheless Truthful
when i
is equal to nine
.
This tabular array illustrates what happens behind the scenes:
Four iterations are completed. The condition is checked again before starting a "fifth" iteration. At this point, the value of i
is 10
, so the condition i <= nine
is Imitation
and the loop stops.
🔸 Infinite While Loops
Now you know how while loops piece of work, but what do y'all think will happen if the while loop status never evaluates to False
?
What are Space While Loops?
Recall that while loops don't update variables automatically (nosotros are in charge of doing that explicitly with our lawmaking). And then there is no guarantee that the loop will finish unless we write the necessary code to make the condition False
at some point during the execution of the loop.
If we don't do this and the condition always evaluates to True
, then we will have an infinite loop, which is a while loop that runs indefinitely (in theory).
Space loops are typically the issue of a bug, simply they can also be acquired intentionally when we desire to repeat a sequence of statements indefinitely until a break
statement is establish.
Permit's see these two types of infinite loops in the examples below.
💡 Tip: A bug is an error in the plan that causes incorrect or unexpected results.
Example of Infinite Loop
This is an instance of an unintentional infinite loop caused by a bug in the program:
# Define a variable i = v # Run this loop while i is less than 15 while i < fifteen: # Print a message print("Hello, Earth!")
Analyze this code for a moment.
Don't you notice something missing in the body of the loop?
That's right!
The value of the variable i
is never updated (information technology'southward always five
). Therefore, the status i < 15
is e'er True
and the loop never stops.
If nosotros run this code, the output volition be an "space" sequence of Hello, Globe!
messages because the body of the loop print("Hello, World!")
will run indefinitely.
Hello, World! Hello, World! Hi, World! Howdy, Globe! Howdy, World! Howdy, World! Hello, Earth! Hullo, World! Howdy, Earth! Howdy, World! Hello, World! Hello, Earth! Hello, World! Hello, World! Hello, World! How-do-you-do, Globe! How-do-you-do, Globe! How-do-you-do, Earth! . . . # Continues indefinitely
To stop the program, we volition need to interrupt the loop manually past pressing CTRL + C
.
When we practice, nosotros will see a KeyboardInterrupt
error similar to this one:
To gear up this loop, we will need to update the value of i
in the torso of the loop to make sure that the condition i < 15
volition somewhen evaluate to False
.
This is 1 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
Great. Now yous know how to fix space loops caused past a bug. You only need to write code to guarantee that the condition will somewhen evaluate to Fake
.
Permit's start diving into intentional infinite loops and how they piece of work.
🔹 How to Make an Infinite Loop with While True
We can generate an infinite 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
argument is found (yous volition learn more than virtually interruption
in merely a moment).
This is the basic syntax:
Instead of writing a condition after the while
keyword, we merely write the truth value straight to indicate that the condition will e'er be Truthful
.
Hither nosotros have an example:
>>> while Truthful: print(0) 0 0 0 0 0 0 0 0 0 0 0 0 0 Traceback (most contempo call last): File "<pyshell#2>", line 2, in <module> print(0) KeyboardInterrupt
The loop runs until CTRL + C
is pressed, merely Python also has a break
statement that we can use directly in our code to stop this type of loop.
The pause
argument
This statement is used to stop a loop immediately. You should think of information technology equally a red "terminate sign" that y'all tin employ in your lawmaking to have more control over the behavior of the loop.
According to the Python Documentation:
Thebreak
statement, similar in C, breaks out of the innermost enclosingfor
orwhile
loop.
This diagram illustrates the bones logic of the break
statement:
This is the basic logic of the break
statement:
- The while loop starts only if the condition evaluates to
True
. - If a
break
argument is establish at whatever indicate during the execution of the loop, the loop stops immediately. - Else, if
suspension
is non found, the loop continues its normal execution and information technology stops when the condition evaluates toFalse
.
We can use break
to stop a while loop when a condition is met at a particular point of its execution, then yous will typically find it within a conditional statement, like this:
while True: # Code if <condition>: break # Code
This stops the loop immediately if the condition is Truthful
.
💡 Tip: You tin can (in theory) write a break
statement anywhere in the torso of the loop. Information technology doesn't necessarily have to exist part of a conditional, only we commonly use it to finish the loop when a given condition is True
.
Here we have an example of break
in a while True
loop:
Let's see it in more particular:
The first line defines a while True
loop that will run indefinitely until a pause
statement is establish (or until information technology is interrupted with CTRL + C
).
while True:
The second 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 % ii != 0:
If information technology is, the message This number is odd
is printed and the interruption
statement stops the loop immediately.
print("This number of odd") interruption
Else, if the input is even , the bulletin This number is fifty-fifty
is printed and the loop starts again.
impress("This number is even")
The loop will run indefinitely until an odd integer is entered considering that is the simply way in which the break
statement will be constitute.
Hither we accept an example with custom user input:
Enter an integer: 4 This number is even Enter an integer: six This number is fifty-fifty Enter an integer: viii This number is even Enter an integer: 3 This number is odd >>>
🔸 In Summary
- While loops are programming structures used to echo a sequence of statements while a condition is
True
. They terminate when the status evaluates toFalse
. - When you write a while loop, you lot need to brand the necessary updates in your lawmaking to make sure that the loop will eventually stop.
- An space loop is a loop that runs indefinitely and it merely stops with external intervention or when a
break
statement is found. - You can stop an infinite loop with
CTRL + C
. - You lot can generate an infinite loop intentionally with
while Truthful
. - The
suspension
argument can be used to finish a while loop immediately.
I actually hope you liked my commodity and found it helpful. At present you know how to piece of work with While Loops in Python.
Follow me on Twitter @EstefaniaCassN and if you lot desire to learn more about this topic, check out my online grade Python Loops and Looping Techniques: Beginner to Advanced.
Learn to code for free. freeCodeCamp'southward open source curriculum has helped more than than xl,000 people get jobs as developers. Get started
Source: https://www.freecodecamp.org/news/python-while-loop-tutorial/
0 Response to "How to Have a While Loop Ask a Question Again Python"
Post a Comment