Search code examples
pythonvar

What is the best way to use a variable from one function in another function (Python)?


I am trying to code something really simple but can't figure out how to use the variable I declared in the first function, in the second function. Any ideas you might have?

import random 

def request_info():
    name = input("What is your name?: ")
    email = input("What is your email?: ")

def print_user_info():
    print("Your name " + name)
    print("Your email " + email)
    num = random.randrange(100_000, 10**8)

Solution

  • I would create a class:

    import random 
    
    class request_info(object):
        def __init__(self):
            self.name = input("What is your name?: ")
            self.email = input("What is your email?: ")
    
        def print_user_info(self):
            print("Your name " + self.name)
            print("Your email " + self.email)
            num = random.randrange(100_000, 10**8)
            return num
        
    r = request_info()
    r.print_user_info()
    
    # What is your name?:  Test
    # What is your email?:  Test@gmail.com
    # Your name Test
    # Your email Test@gmail.com
    # 90584743