Amritanshu Verma
Amritanshu Verma

Reputation: 43

how to find that how many times a while loop has get executed?

Sample program in which while loop is illustrated:

answer="0"
while answer!="4":
    answer=input("What is 2 + 2?")
    if answer!="4":
        print("Wrong...Try again.")
    else:
        print("Yes! 2 + 2 = 4")

Here the loop will execute till the user gives the correct answer, i.e. 4.

I want to add another feature in the above code which prints how many attempts the user took to give the correct answer.

print("You gave correct answer in attempt",answer)

But I am not getting any idea how to do it.

Upvotes: 1

Views: 116

Answers (3)

Dave
Dave

Reputation: 4356

Currently working through some tutorials on Python, so if it doesn't work, do excuse my n00b level...

answer=0
attempts = 0
while answer!=4:
    answer=input("What is 2 + 2?")
    if answer!=4:
        print("Wrong...Try again.")
        attempts = attempts + 1
    else:
        print("Yes! 2 + 2 = 4")

print("You gave correct answer in %d attempts" % attempts)

Upvotes: 0

Daniel
Daniel

Reputation: 42778

Convert the while-loop into a for-loop:

from itertools import count

for attempts in count(1):
    answer = input("What is 2 + 2?")
    if answer == "4":
        break
    print("Wrong...Try again.")
print("Correct in {} attempts!".format(attempts))

Upvotes: 2

AlanK
AlanK

Reputation: 9853

Create a variable which stores the amount of attempts the user has taken:

attempts = 0 

while True:
    answer = int(raw_input("What is 2 + 2?"))
    attempts += 1
    if answer == 4: 
        print("Yes! 2 + 2 = 4")
        break
    print "Wrong.. try again"

print "It took {0} amount of attempts".format(attempts)

Upvotes: 2

Related Questions