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
Output :
Hi i have a question to ask you about while loop
I have 2 examples here hope you can explain to me !
a = 1
b = 10
While a< b:
a+=1 #increment at top
Print(a)
Output : 2,3,4,5,6….
a = 1
b = 10
While a< b:
Print(a)
A = a+1 # increment at bottom
Output : 1,2,3,4,5,6…
Can you explain why i put the increment at the top the output start from 2 but when i put at the bottom it starts from 1
Pleas help!!!
HI, in example one with the increment on top – the variable “a” is being incremented BEFORE printing.
consider it this way: your program enters in to the loop while a = 1. the FIRST step of the loop is to ADD 1 to a, amking a = 2. the NEXT step of the loop is to print. therefore the loop will never print 1.
in your second example, you are printing BEFORE incrementing so that is why the original value a = 1 is being printed.