close

How to add a counter to a while loop?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to add a counter to a while loop in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to add a counter to a while loop?

  1. How to add a counter to a while loop?

    In general it should look like this:
    i = 0 while i < max_guesses: i+=1 # here is your code

  2. add a counter to a while loop

    In general it should look like this:
    i = 0 while i < max_guesses: i+=1 # here is your code

Method 1

In general it should look like this:

i = 0
while i < max_guesses:
    i+=1
    # here is your code

Method 2

The Pythonic way is

max_guesses = 5
guessed = False
for wrong_guesses in range(max_guesses):
    if A==round(Ac,2):
      print("correct")
      guessed = True
      break 
    ...
else:
  print("You have exceeded the maximum of {} guesses".format(max_guesses)) 
if not guessed:
  wrong_guesses += 1

This way the loop is executed at most max_guesses times. The else block is only executed if the loop did not end because of a break statement i.e. when there was no correct guess.

Note the if not guessed at the end is to cater for counting the last incorrect guess because the loop ends with wrong_guesses == (max_guesses – 1 in that case). This is because range is an iterator over the interval [0, max_guesses) (excluding the upper limit).

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read