2

I am writing a function where it gets input from the user and sets the variable answer to the answer the user gives. I am printing answer outside of the function, but for some reason, it doesn't print anything.

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.
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • the variables that are declared inside a function are called local variables. the values assigned to the variables inside the function will stay in the function only. In order to get the desired output add a print or return statement in the function return answer or print(answer) – Yagami_Light Mar 08 '22 at 04:37

2 Answers2

0

answer inside ask() creates a fresh variable called answer; it does not refer to the variable declared above ask().

The cleanest way to resolve this is to return the user's input from ask() and then directly assign it to answer. (You could also use the global keyword, but that's generally considered bad practice.)

def ask(question):
    return input(question)
answer = ask("how are you ")
print(answer)
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • Is there any possible way for me to refer to a variable inside of a function without having to set the "answer" variable to the asking function outside of the function? –  Mar 08 '22 at 04:38
  • Yes, you can use the `global` keyword. Use your original code, but insert `global answer` as the first line of the `ask()` function body. That being said, this can make your code pretty hard to read, so use this sparingly. – BrokenBenchmark Mar 08 '22 at 04:39
0

You must print answer:

  1. inside of ask function, or
  2. return answer, catch it and then print it

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

or one line:

print(ask("how are you "))