[SOLVED] Unable to retrieve variable assigned in function

Issue

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.

Solution

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 "))

Answered By – Marcel Suleiman

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.