0
number = 7
def magicnumber (guess):
   if number<guess:
        print ("too high")
    elif number>guess:
         print ("too low")
    elif number == guess:
         print ("well done")
      return magicnumber

Above is my code for my magic number guessing program. My question is how to insert a loop counter. I did some research on loop counter integration, and many people have said to use the enumerate function, problem is I have no idea how to use such a function and if it is appropriate in my case. Normally, I jus declare a counter variable as 0 then use the += function to add 1 to that variable but in my case this does not work as I cant declare the variable before the def magicnumber (guess) line and if I were to declare it, the counter would revert back to 0 after the return. I am therefore enquiring how to add a loop count as I only want the user to have 5 guesses.

Thanks

Dingo F
  • 25
  • 3

2 Answers2

0
counter = 5
while counter > 0:
    guess = int(raw_input())
    if magicnumber(guess) == number:
        break
    counter -= 1

Another approach:

for i in range(5):
    guess = int(raw_input())
    if magicnumber(guess) == number:
        break
xiº
  • 4,605
  • 3
  • 28
  • 39
-2

Try using the answer from here: That's what static variables are for (among other things). That would result in the following code

number = 7
def magicnumber (guess):
    magicnumber.counter += 1
    if(magicnumber.counter <= 5):
         if number<guess:
            print ("too high")
         elif number>guess:
            print ("too low")
         elif number == guess:
             print ("well done")
             magicnumber.counter = 0#If you want to reset the counter
         return
    else:
        print "Out of trials!"
        return

magicnumber.counter = 0
Community
  • 1
  • 1
arc_lupus
  • 3,942
  • 5
  • 45
  • 81
  • For future reference, why did this post get down voted? It was by far the best answer that met my needs so why the down votes? Thanks though – Dingo F Apr 03 '16 at 17:56
  • The downvotes are there because I misunderstood your question and posted an answer. This answer was clearly wrong, and until I could correct it, I got those downvotes. – arc_lupus Apr 03 '16 at 18:24