NameError:未定义猜测

时间:2016-02-08 18:08:34

标签: python nameerror

我刚刚开始使用python,我想知道为什么我的变量猜测没有定义。我觉得它好像是一个缩进问题但是一旦我改变了缩进,我通常会遇到语法错误,任何帮助理解这个问题的人都会非常感激。

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!")

1 个答案:

答案 0 :(得分:1)

这不会在我的计算机上引发任何错误。请注意,如果要实际运行代码,则必须调用game()函数。

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