1

In the guessing game, I want the count to be the number of guesses variable and it to print the value when you win the game. Whenever I try to add the count = count + 1 line of code under the else part I keep getting loads of errors.

import random

from random import randint

secret = randint(0,11)
count = 1

def guessing():

    print ("Guessing easy: The secret number will stay the same every turn")
    guess = int(input("Guess a number from 1 to 10 "))

    if secret == guess:
        print ("Your guess was", guess)
        print ("Well done, you win")
        print ("It took you", count, "guessing to win")
        startgame()
    else:
        print ("Your guess was",guess)
        print ("Sorry, your guess was wrong. Please try again""\n")
        guessing()

def guessinghard():
    print ("Guessing hard: The secret number will change every turn")
    secret = randint(0,11)
    guess = int(input("Guess a number from 1 to 10 "))

    if secret == guess:
        print ("Your guess was", guess)
        print ("Well done, you win")
        print ("It took you ", count, " guessing to win")
        startgame()
    else:
        print ("Your guess was", guess)
        print ("Sorry, your guess was wrong. Please try again")
        guessinghard()

def startgame():
    game = input("Would you like to play easy or hard ")

    if game == "easy":
        guessing()
    elif game == "hard":
        guessinghard()
    else:
        print("Please choose easy or hard")
        startgame()

startgame()

The errors I get are:

Traceback (most recent call last):
  File "H:/Modules (Year 2)/Advanced programming/Python/Week 2 - Review and Arrays/
Iteration Exercise -  Secret Number.py", line 52, in <module>
    startgame()

  File "H:/Modules (Year 2)/Advanced programming/Python/Week 2 - Review and Arrays/
Iteration Exercise -  Secret Number.py", line 45, in startgame
    guessing()

  File "H:/Modules (Year 2)/Advanced programming/Python/Week 2 - Review and Arrays/
Iteration Exercise -  Secret Number.py", line 21, in guessing
    count = count + 1

UnboundLocalError: local variable 'count' referenced before assignment
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ross
  • 303
  • 1
  • 4
  • 19

1 Answers1

1

The count variable was declared outside the function that's using it. You could either declare that it's global, inside the function:

global count

Or pass it around as a parameter each time you call guessing(), as it's a recursive function:

def guessing(count):

Also, the code posted in the question doesn't show where the actual count variable is being incremented.

Óscar López
  • 232,561
  • 37
  • 312
  • 386