omgugl.blogg.se

Python while loop
Python while loop








python while loop

When the value of x = 7 then the break statement will be executed and we will jump out of the while loop body.įollowing is the output of the above code. In the following Python program we are going to print integer numbers from 1 to 10 but we will jump out of the while loop when we encounter number 7. We use the break keyword to come out of the while loop body even if the condition of the loop is satisfied.

#Python while loop code

In the following Python code we are printing only the odd numbers between 1 to 20 both inclusive. When the value of x becomes 11 the condition fails so we come out of the while loop. Then we are incrementing the value of x by 1.Īfter incrementing the value of x we are again checking the loop condition and repeating the body. Inside the body of the while loop we are printing the value of x. So, as long as value of x is less than or equal to 10 we are going to execute the body of the loop. We start by initialising the variable x = 1.įor the condition we are checking is x <= 10. The above code will print the following output. In the following Python program we are printing integer number 1 to 10 using while loop. Inside the body of the while loop we keep updating the condition of the loop so that we can come out of it.

python while loop

Where, condition is some condition and if it is satisfied then the body of the while loop is executed otherwise, it is ignored. We use the while keyword to create a while loop in Python. So, to solve this task we take help of a loop that executes the print statement for us for 1000 or N number times. You can write the print statement 1000 times which we both know is very tiring and not the best way to solve the problem. Imagine you have to print "Hello World" text 1000 times.

python while loop

We use loop to complete repeating task with ease. In this tutorial we will learn about while loop in Python.Ī loop is a block of code that gets executed over and over again as long as the given condition is satisfied.










Python while loop