How to Decrement a Loop in Python

0 min read 115 words

If you need to decrement a loop in Python, then you can do the following:

How to Decrement a loop in Python using -1

The optional third argument you can pass to the range function is the order.

The default order is to count up / increment, while the -1 value, is to count down / decrement.

for i in range(3, 0, -1):
  print(i)

Output: 3 2 1

How to Decrement a loop in Python using while

You can also use a while loop and set the value to the upper bound, and then decrement while in the loop itself.

i = 3
while (i > 0):
  print(i)
  i = i-1

Output: 3 2 1

Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts