Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Record how many times a while loop runs? - python

Tags:

python

loops

Imagine this:

You have a while loop

You want to know how many times it ran

What should you do???

Now I hear you say, what is the context?

Context: I am writing this program in Python which thinks of a number between 1 and 100, and you are to guess it. The guessing takes part in a while loop (please have a look at the code below) but I need to know how many guesses are made.

So, this is what I need:

print("It took you " + number_of_guesses + " guesses to get this correct.")

This is the complete code at Gist: https://gist.github.com/anonymous/1d33c9ace3f67642ac09

Please remember: I am using Python 3x

Thanks in advance

like image 234
Turbo Avatar asked Dec 01 '22 02:12

Turbo


2 Answers

count = 0

while x != y::
   count +=1 # variable will increment every loop iteration
   # your code


print count
like image 114
jramirez Avatar answered Dec 04 '22 12:12

jramirez


just for fun , your whole program in 4 (somewhat readable) lines of code

sentinel = random.randint(1,10)
def check_guess(guess):
    print ("Hint:(too small)" if guess < sentinel else "Hint:(too big)")
    return True

total_guesses = sum(1 for guess in iter(lambda:int(input("Can you guess it?: ")), sentinel) if check_guess(guess)) + 1
like image 29
Joran Beasley Avatar answered Dec 04 '22 10:12

Joran Beasley