Oct-21-2019, 12:12 AM
(Oct-20-2019, 04:07 PM)mayadob Wrote: [ -> ]What if I call it with:
length(c, d) length(e,f)
As Ichabod said:
(Oct-20-2019, 05:45 PM)ichabod801 Wrote: [ -> ][ ... ] somehow you need to store the name.
so maybe you could store the names of the variables and the values of those variables in a list, named, let's say data1, where after the name of the variable between quotes, we put the value of that variable, like the following:
data1 = ['a', 5, 'b', 3, 'c', 7, 'd', 2, 'e', 1, 'f', 9]As you want to manage the names of those variables and their values within a function, I created a generic function which I named length(x, y) for a generic couple of variables named x, y to add the values of those variables, while at the same time, using also the names of those variables.
If we have a certain character x in a list named data1, we can get its position (index) in the list, using the command data1.index(x). If we called this value, xVariableValue, we can use the following expression:
xVariableValue = data1.index(x)This expression is quite useful for our purpose, as it gives us the index(position) of the character x (meaning a generic variable) in the list named data1 and we store it in what we called xVariableValue. Therefore, if we asked for the item in that position in that list, we have the name of the variable. According to our convention when we created the list, if the name of a variable is at an index of xVariableValue, its value is the next item, that is to say, its value is at an index of xVariableValue+1. So:
data1[xVariableValue] gives us the name of the generic variable x,
data1[xVariableValue+1] gives us the value of the generic variable x,
data1[yVariableValue] gives us the name of the generic variable y,
data1[yVariableValue+1] gives us the value of the generic variable y.
Applying the same logic, we can then fill the missing coding bits of our function and program, applying the generic length(x, y) function, for example, to 4 pairs of variables from our list:
data1 = ['a', 5, 'b', 3, 'c', 7, 'd', 2, 'e', 1, 'f', 9] def length(x, y): xVariableValue = data1.index(x) yVariableValue = data1.index(y) print(f'''\n{data1[xVariableValue]} = {data1[xVariableValue+1]}\n\ {data1[yVariableValue]} = {data1[yVariableValue+1]}\n\ The length of '{data1[xVariableValue]}{data1[yVariableValue]}' is {data1[xVariableValue+1] + data1[yVariableValue+1]}.\n''') length('a', 'b') length('c', 'd') length('e', 'f') length('c', 'f')and that little program produces the following output:
Output:a = 5
b = 3
The length of 'ab' is 8.
c = 7
d = 2
The length of 'cd' is 9.
e = 1
f = 9
The length of 'ef' is 10.
c = 7
f = 9
The length of 'cf' is 16.
I hope that this is what you wanted and that I have explained it more clearly now.All the best,