Decrement in while loop in Python
This tutorial will help you to understand how to do decrement in while loop in Python.
In programming, we use a loop to execute repeatedly a block of statements until a specific condition (loop-control statement) is met. In Python, we have two different types of loop. Those are –
- while loop
- for loop
In a while loop, we can execute the statements inside it’s loop body repeatedly as long as the loop control statement is true.
Syntax – while loop
while (loop-control statement): #loop body statement(s)
How to perform decrement in while loop in Python
If the loop-control statement is true, Python interpreter will start the executions of the loop body statement(s). After that, we need to use an Arithmetic Operator/Counter to increment or decrement it’s value. After incrementing/decrementing it’ll again check the loop-control statement whether it’s true or not. If the loop-control statement is still true it’ll run the statements inside the loop body again otherwise it’ll exit from the loop. In this article, I’ll discuss about decrement in a while loop in Python. To understand this concept let’s take an example:
n=10 while (n>=0): #loop control-statememt print (n) #loop body n-=1 #decrementing the value by 1
10 9 8 7 6 5 4 3 2 1 0
In this above example, the value of variable n is 10. Then we started a while loop with a condition that it should run the loop until the value variable of n becomes zero. Inside the loop body, we gave only two instructions. The first one is to print the value of n and the second one is to decrement the value of n by 1. And so the output came like this starting from 10 to 0.
I hope now you are familiar with the concept decrement in while loop in Python.
Read also: While loop in Python