Skip to content Skip to sidebar Skip to footer

How to Incorporate While Loop for Would You Like to Do It Again

Python Do While – Loop Example

Loops are a useful and frequently used feature in all modernistic programming languages.

If you want to automate a specific repetitive chore or preclude yourself from writing repetitive code in your programs, using a loop is the best pick for that.

Loops are a gear up of instructions that run repeatedly until a status is met. Let's learn more well-nigh how loops piece of work in Python.

Loops in Python

There are ii types of loops built into Python:

  • for loops
  • while loops

Permit's focus on how y'all can create a while loop in Python and how it works.

What is a while loop in Python?

The full general syntax of a while loop in Python looks similar this:

                while condition:     execute this code in the loop's body                              

A while loop will run a slice of lawmaking while a condition is True. It will keep executing the desired set of code statements until that condition is no longer True.

A while loop will always offset check the status before running.

If the status evaluates to True then the loop volition run the lawmaking within the loop'due south body.

For example, this loop runs equally long as number is less than ten:

                number = 0 while number < 10:     impress(f"Number is {number}!")     number = number + one                              

Output:

                Number is 0! Number is 1! Number is 2! Number is 3! Number is 4! Number is v! Number is vi! Number is 7! Number is 8! Number is 9!                              

Here, the variable number is prepare to 0 initially.

Earlier 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 panel.

number is then incremented by ane. The condition is re-evaluated and it is again True, then the whole process repeats until number is equal to ix.

This time Number is ix! is printed and number is incremented, but at present number is equal to 10 so the condition is no longer met and therefore the loop is terminated.

It'southward possible that the while loop never runs if information technology doesn't meet the status, similar in this example:

                number = 50 while number < x :     print(f"Number is {number}!")                              

Since the condition is always False, the instructions in the loop'south torso don't execute.

Don't create infinite loops

As you lot saw from the example above, while loops are typically accompanied by a variable whose value changes throughout the elapsing of the loop. And it ultimately determines when the loop volition end.

If you lot practice non add this line, you will create an space loop.

number will not be incremented and updated. It will always be set and remain at 0 and therefore the status number < 10 will be True forever. This means that the loop will continue to loop forever.

                                  # don't run this  number = 0 while number < 10:     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! ...                              

It runs infinitely.

It is the same as doing this:

                                  #don't run this while True:     print("I am e'er truthful")                              

What if y'all notice yourself in a state of affairs like this?

Press Control C to escape and stop the loop.

What is a do while loop?

The general syntax of a practice while loop in other programming languages looks something similar this:

                do {   loop block statement to be executed;   } while(status);                              

For case, a do while loop in C looks like this:

                #include <stdio.h>   int primary(void)  {    int i = 10;    do {       printf("the value of i: %i\n", i);       i++;       }   while( i < 20 );  }                              

What is unique in practise while loops is the fact that the code in the loop block volition exist executed at least one time.

The code in the statement runs 1 fourth dimension and so the status is checked just after the lawmaking is executed.

So the code runs one time first and so the condition is checked.

If the condition checked evaluates to true, the loop continues.

There are cases where you would want your code to run at to the lowest degree one fourth dimension, and that is where do while loops come up in handy.

For example, when y'all're writing a program that takes in input from users you may enquire for but a positive number. The lawmaking will run at least in one case. If the number the user submits is negative, the loop volition keep on running. If it is positive, information technology will stop.

Python does non have built-in functionality to explicitly create a do while loop like 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 do while loop in Python, you lot need to alter the while loop a bit in order to get similar behavior to a do while loop in other languages.

As a refresher so far, a do while loop will run at least once. If the condition is met, and then it will run over again.

The while loop, on the other hand, doesn't run at least once and may in fact never run. It runs when and only when the condition is met.

Then, let'southward say nosotros have an example where we want a line of code to run at least once.

                secret_word = "python" counter = 0  while True:     word = input("Enter the secret discussion: ").lower()     counter = counter + one     if word == secret_word:         intermission     if give-and-take != secret_word and counter > 7:          break                              

The code will run at to the lowest degree i time, asking for user input.

It is always guaranteed to run at least once, with True, which otherwise creates an space loop.

If the user inputs the right clandestine discussion, the loop is terminated.

If the user enters the wrong secret give-and-take more than than 7 times, then the loop will exist completely exited.

The pause statement allows y'all to control the flow of a while loop and not end up with an infinite loop.

break will immediately end the current loop all together and break out of it.

So this is how yous create the a similar effect to a practise while loop in Python.

The loop always executes at to the lowest degree once. It will continue to loop if a condition is not met and and then terminate when a condition is met.

Decision

Y'all at present know how to create a do while loop in Python.

If you're interested in learning more virtually Python, you can scout the 12 Python Projects video on freeCodeCamp's YouTube aqueduct. You'll get to build 12 projects and information technology's geared towards beginners.

freeCodeCamp also has a free Python Certification to help y'all gain a good understanding and a well rounded overview of the important fundamentals of the language.

Yous'll as well go to build 5 projects at the terminate of the course to do what you've learned.

Thanks for reading and happy learning!



Acquire to code for gratis. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Become started

floresfrompont.blogspot.com

Source: https://www.freecodecamp.org/news/python-do-while-loop-example/

Post a Comment for "How to Incorporate While Loop for Would You Like to Do It Again"