Home > database >  How do I use different variables depending on the input of a function?
How do I use different variables depending on the input of a function?

Time:06-08

I'm trying to give a number to a function where that number will be used to determine which variables will be used. I think it would look something like this:

num1 = 61
nun2 = 48
num3 = 27

char1 = "a"
char2 = "b"
char3 = "c"

color1 = "red"
color2 = "blue"
color3 = "green"

def func (inputnumber):

    # don't know what to put in here

    return [num,char,color]

I have a set of variables numbers 1,2, and 3. For my function, I will give an input of 1,2, or 3 (I guess it has to be str(inputnumber))and the function will take that number and determine which variables to use to process data. For example, if I input 1, I would like to get a list of [61, "a","red].

Is there a way to do this? I do know about dictionaries but I don't want to make or store new variables and would like to use the ones that already exist.

CodePudding user response:

Do not have those variables in the first place. Instead, use appropriately structured data. Since you want to choose the results according to a numeric index, a list or tuple is appropriate. So to start, instead of separate num1 = 61, num2 = 48, num3 = 27, we could make a single tuple of values: nums = (61, 48, 27). Now we can access that by index, starting at 0: nums[0] is equal to 61, nums[1] is equal to 48, and nums[2] is equal to 27. Since it works the same way regardless of the number, we can use inputnumber to do the selection.

So to start, that gives us:

nums = (61, 48, 27)
chars = ('a', 'b', 'c')
colors = ('red', 'blue', 'green')

def func(selector):
    selector -= 1 # so that input 1 will correspond to index 0 etc.
    return (nums[selector], chars[selector], colors[selector])

However, we can do better. Just like how we are grouping related data to return it, we can group the related possible return values. Use a tuple to represent everything that is returned for a given input. Thus:

results = ((61, 'a', 'red'), (48, 'b', 'blue'), (27, 'c', 'green'))

def func(selector):
    return results[selector-1]

CodePudding user response:

As others have commented, a better, more standard approach would probably be to use a list or dictionary to store the values. That said, if for some reason you really want to refer to variables dynamically by name, you can use the built-in globals() function which returns a dictionary of all global variables keyed by the variable name. You can build that key as string dynamically to access the variable you need. There is also a corresponding locals() function as well if the variables are actually locals instead of a globally scoped.

def func(inputnumber):
   s = str(inputnumber)
   g = globals()
   return [g['num'   s], g['char'   s], g['color'   s]]

  • Related