无法检索函数中分配的变量

Unable to retrieve variable assigned in function

我正在编写一个函数,它从用户那里获取输入并将变量 answer 设置为用户给出的答案。我在函数外打印 answer,但由于某种原因,它没有打印任何东西。

answer = " "   # set empty in the start
def ask(question):
    answer = input(question) # sets the answer to the user's input
ask("how are you ")
print(answer)  # ends up printing nothing.

answerask() 中创建一个名为 answer 的新变量;它确实 而不是 引用上面声明的变量 ask().

解决这个问题最干净的方法是 return 用户从 ask() 输入,然后直接分配给 answer。 (您也可以使用 global 关键字,但这通常被认为是不好的做法。)

def ask(question):
    return input(question)
answer = ask("how are you ")
print(answer)

您必须打印答案:

  1. ask 函数内部, 或
  2. return回答,抓到然后打印出来

answer = " "   # set empty in the start
def ask(question):
    answer = input(question)
    return answer
    
answer = ask("how are you ")
print(answer)

或一行:

print(ask("how are you "))