【问题标题】:NameError: guesses not definedNameError:猜测未定义
【发布时间】:2016-02-08 18:08:34
【问题描述】:

我刚刚开始使用 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!")

【问题讨论】:

  • 函数 game() 中的所有内容都必须在该函数下一致缩进。您的 while 循环存在于该函数之外,并且猜测仅在该函数内具有范围。

标签: python nameerror


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多