Unable to retrieve variable assigned in function
Question:
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.
Answers:
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)
You must print answer:
- inside of ask function,
or
- 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 "))
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.
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)
You must print answer:
- inside of ask function,
or - 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 "))