Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use data from inside of a function out side of the function in Python?

So I am new to python, I’m taking classes online, self learning, but I need to know how to pull information out of one function and use it elsewhere in my code.

for example:

def yes_responce():
    print("Good! I'm glad i got that right!!!")

def no_responce():
    print("Oh no! I'm sorry about that! Let me try that again")
    greeting()
    
def greeting():
    name = input("Hello, What is your name?")
    age = input("How old are you?")
    print("okay,")
    print("I understood that you name is", name, "and that you are", age, "years old.")
    menu1 = input("Am I correct? enter y for yes, or n for no.")
    if menu1 == "y":
        yes_responce()
    if menu1 == "n":
        no_responce()
    return {menu1}

greeting()

print(menu1) 

the function works great, but how would I be able to call the name or age or menu1 data outside of this function? I’m sorry for asking such a noob question, but I just cant figure it out!
in my head, print(menu1)should print y.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you define a variable inside of a function, it’s called a local variable and is only accessible within that function unless you include it in the return statement. So to access the variables after running the greeting function, you could write:
If you want a variable to be accessible globally, then you could write:

    def greeting():
      name = input("Hello, What is your name?")
      age = input("How old are you?")
      print("okay,")
      print("I understood that you name is", name,
          "and that you are", age, "years old.")
      menu1 = input("Am I correct? enter y for yes, or n for no.")
      if menu1 == "y":
          yes_responce()
      if menu1 == "n":
          no_responce()
      return name, age, menu1
    
    name, age, menu = greeting()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading