Python How to Run Main Again
Loops are a useful and frequently used feature in all modern programming languages.
If yous desire to automate a specific repetitive task or prevent yourself from writing repetitive code in your programs, using a loop is the all-time option for that.
Loops are a set up of instructions that run repeatedly until a status is met. Permit's learn more about how loops work in Python.
Loops in Python
At that place are two types of loops congenital into Python:
-
for
loops -
while
loops
Permit'south focus on how you can create a while
loop in Python and how it works.
What is a while loop in Python?
The general syntax of a while
loop in Python looks similar this:
while condition: execute this lawmaking in the loop's body
A while loop volition run a piece of code while a condition is True. It will go along executing the desired set of lawmaking statements until that status is no longer True.
A while loop volition always beginning check the condition earlier running.
If the condition evaluates to True
so the loop volition run the code inside the loop's trunk.
For instance, this loop runs as long equally number
is less than 10
:
number = 0 while number < 10: impress(f"Number is {number}!") number = number + 1
Output:
Number is 0! Number is ane! Number is 2! Number is 3! Number is four! Number is v! Number is 6! Number is 7! Number is 8! Number is nine!
Here, the variable number
is set to 0
initially.
Before any code is run, Python checks the condition (number < 10
). It evaluates to Truthful so the impress statement gets executed and Number is 0!
is printed to the console.
number
is and so incremented by 1
. The condition is re-evaluated and it is again True, and then the whole procedure repeats until number
is equal to ix
.
This fourth dimension Number is 9!
is printed and number
is incremented, merely now number
is equal to ten
and then the condition is no longer met and therefore the loop is terminated.
It'southward possible that the while
loop never runs if it doesn't come across the status, like in this example:
number = 50 while number < 10 : print(f"Number is {number}!")
Since the condition is always False, the instructions in the loop'south body don't execute.
Don't create infinite loops
As yous saw from the example above, while
loops are typically accompanied past a variable whose value changes throughout the duration of the loop. And it ultimately determines when the loop will finish.
If yous practice not add this line, you will create an infinite loop.
number
will not exist incremented and updated. It will ever be gear up and remain at 0
and therefore the condition number < 10
will be Truthful forever. This means that the loop will continue to loop forever.
# don't run this number = 0 while number < ten: print(f"Number is {number}!")
Output:
Number is 0! Number is 0! Number is 0! Number is 0! Number is 0! Number is 0! Number is 0! ...
Information technology runs infinitely.
It is the same equally doing this:
#don't run this while True: print("I am always true")
What if you find yourself in a situation like this?
Press Control C
to escape and end the loop.
What is a exercise while loop?
The general syntax of a exercise while
loop in other programming languages looks something like this:
do { loop block statement to exist executed; } while(condition);
For example, a practice while loop in C looks similar this:
#include <stdio.h> int main(void) { int i = 10; do { printf("the value of i: %i\n", i); i++; } while( i < xx ); }
What is unique in do while loops is the fact that the code in the loop block will exist executed at least i time.
The code in the argument runs 1 time and so the status is checked simply after the code is executed.
And then the code runs in one case first and so the condition is checked.
If the condition checked evaluates to true, the loop continues.
There are cases where you lot would want your code to run at least ane time, and that is where do while loops come in handy.
For example, when you're writing a plan that takes in input from users you may ask for only a positive number. The code will run at least in one case. If the number the user submits is negative, the loop will keep on running. If it is positive, it will terminate.
Python does non have built-in functionality to explicitly create a do while
loop similar other languages. But information technology is possible to emulate a do while
loop in Python.
How to emulate a do while loop in Python
To create a exercise while
loop in Python, y'all need to alter the while
loop a bit in order to get similar behavior to a practise while
loop in other languages.
Equally a refresher then far, a do while
loop volition run at least in one case. If the condition is met, then it will run over again.
The while
loop, on the other mitt, doesn't run at to the lowest degree once and may in fact never run. Information technology runs when and only when the condition is met.
So, let'southward say we have an example where nosotros want a line of code to run at least one time.
secret_word = "python" counter = 0 while True: word = input("Enter the secret word: ").lower() counter = counter + 1 if discussion == secret_word: break if word != secret_word and counter > 7: break
The lawmaking volition run at least ane fourth dimension, asking for user input.
Information technology is e'er guaranteed to run at to the lowest degree once, with Truthful
, which otherwise creates an infinite loop.
If the user inputs the correct secret word, the loop is terminated.
If the user enters the wrong hush-hush give-and-take more than than 7 times, then the loop will be completely exited.
The break
statement allows yous to control the flow of a while
loop and not end up with an infinite loop.
break
will immediately terminate the electric current loop all together and interruption out of it.
So this is how you create the a similar effect to a do while
loop in Python.
The loop always executes at least one time. It will continue to loop if a condition is not met and so finish when a condition is met.
Conclusion
Y'all now know how to create a practice while
loop in Python.
If you're interested in learning more about Python, you can lookout man the 12 Python Projects video on freeCodeCamp'southward YouTube channel. You'll get to build 12 projects and information technology's geared towards beginners.
freeCodeCamp as well has a gratuitous Python Certification to assistance you gain a good agreement and a well rounded overview of the of import fundamentals of the language.
Yous'll too get to build five projects at the cease of the grade to practice what yous've learned.
Thanks for reading and happy learning!
Learn to code for free. freeCodeCamp's open source curriculum has helped more than than 40,000 people get jobs as developers. Get started
Source: https://www.freecodecamp.org/news/python-do-while-loop-example/