Home Ask Login Register

Developers Planet

Your answer is one click away!

Prolificstewie February 2016

NameError: guesses not defined

I'm just starting out on python and I'm wondering exactly why my variable guesses is not defined. I feel as if it's a indentation issue but once I change the indentation I usually come upon a syntax error any help understanding this issue would be greatly appreciated.

import random

def game():

  guesses = []
  secret_num = random.randint(1, 10)

while len(guesses) < 5:
  try:
     guess = int(input("Guess a number between 1 and 10 "))
  except ValueError:
     print("{} isn't a number!".format(guess))
  else:
      if guess == secret_num:
          print("You got it! My number was {}".format(secret_num))
          break
      elif guess < secret_num:
          print("My number is higher than {}".format(guess))

      else:
          print("My number is lower tha {}".format(guess))
      guesses.append(guess)
else:
    print("You didn't get it my secret number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/N")
if play_again.lower() != 'n':
   game()
else:
    print("Bye thanks for playing!")

Answers


Garrett R February 2016

This doesn't throw any errors on my computer. Note you'll have to call the game() function if you want to actually run the code.

import random

def game():

    guesses = []
    secret_num = random.randint(1, 10)

    while len(guesses) < 5:
      try:
         guess = int(input("Guess a number between 1 and 10 "))
      except ValueError:
         print("{} isn't a number!".format(guess))
      else:
          if guess == secret_num:
              print("You got it! My number was {}".format(secret_num))
              break
          elif guess < secret_num:
              print("My number is higher than {}".format(guess))

          else:
              print("My number is lower tha {}".format(guess))
          guesses.append(guess)
    else:
        print("You didn't get it my secret number was {}".format(secret_num))
    play_again = input("Do you want to play again? Y/N")
    if play_again.lower() != 'n':
       game()
    else:
        print("Bye thanks for playing!")

game()   # to run the code

Post Status

Asked in February 2016
Viewed 2,920 times
Voted 14
Answered 1 times

Search




Leave an answer


Quote of the day: live life