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

Time:07-10

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.

CodePudding user response:

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

CodePudding user response:

Look at this link:

https://www.geeksforgeeks.org/python-return-statement

It will clear all your doubts

  • Related