未定义变量

时间:2019-06-28 02:53:37

标签: python python-3.x

当我尝试运行它时,会收到未定义 word game()有问题的输出。我可以帮忙吗?

def game():
  word = input("Gimme a word: ")
  if word.isalpha():
    print("It's all letters")
    word = answer
  else:
    print('nope')
    game()

game()
print(answer)

2 个答案:

答案 0 :(得分:1)

我不知道您想要这段代码做什么,所以我假设如果您输入仅包含字母的字符串,它将打印出答案

answer = 'asdasdasdasdanswer'

def game():
  while True:
    word = input("Gimme a word: ")
    if word.isalpha():
      print("It's all letters")
      return answer
    else :
      print("nope")

print(game())

或者如果您要编辑单词的值

def game():
  while True:
    word = input("Gimme a word: ")
    if word.isalpha():
      print("It's all letters")
      return word
    else :
      print("nope")

answer = game()
#do something with answer
print(answer)

答案 1 :(得分:0)

这是因为您没有变量 answer

因此声明一个全局变量答案

answer = '' 
def game():
  word = input("Gimme a word: ")
  if word.isalpha():
    print("It's all letters")
    word = answer
  else:
    print('nope')
    game()

game()
print(answer)