Skip to content Skip to sidebar Skip to footer

Calling Variables From User Defined Functions

The code is probably buggy I just used it to illustrate my point(but feel free to point out any mistakes) I need to know how to call a variable i defined as an input in a user defi

Solution 1:

You need to return the values inputed in createIdentity, and then pass the returned values to recallIdentity. A variable name that's defined in one function is not the same variable as a variable with the same name in a different function.

I'd do it with a dictionary, thusly:

import time

def createIdentity():
    user = dict()
    print ("Please Enter your details below")
    time.sleep(1)
    user['name'] = input("What is your name?")
    time.sleep(1)
    user['age'] = input("How old are you?")
    time.sleep(1)
    user['gender'] = input("Are you male or female?")
    return user

def recallIdentity(user_out):
    print("Your name is " + user_out['name'] + "you are " + user_out['age'] + "And you are a " + user_out['gender'] + "!")

user_dict = createIdentity()
recallIdentity(user_dict)

Solution 2:

By default, functions are entirely self-contained. You have to either compute your variables, or pass them in as parameters, or return them from other functions (another form of computing).

However, there are such things as global variables. With global variables, you can set them in one function, access them in another function, and the value will carry over.

In python, you must tell python the variable is global inside each function where you use it as a global.

For example:

deff():
  x = 1# NOT globaldefg():
  global x
  x = 1# Global x.defh():
  print("X is %d" % x)   # NOT a global xdefi():
  global x
  print("X is %d" % x)    # Global x.

In your example, I believe you want the global behaviors - the g() and i() functions.

Post a Comment for "Calling Variables From User Defined Functions"