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
count = 0
while x != y::
count +=1 # variable will increment every loop iteration
# your code
print count
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With