How to declare a variable based on value of another Integer? [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
On my recent project I am facing with new obstruction where I need to declare a variable based on value of another string.
What I need:
'Hai'= 2
The String Hai is initialized at variable x,
x='hai' then I need 'hai'= 2
Now all I want is the value of x to point to a int (different int for different values of x).
So if,
x='bye'
then,
'bye'=20

You need to get a dictionary as #Saadat said:
x = {'hai': 2, 'bye': 20}
Now
x['hai']
Will give 2 and the other key will give 20
Or:
y='hai'
z = x[y] #z=2
Also another worse approach:
if x == 'hai':
hai = 2
elif x == 'bye'
bye = 20
...

As mentioned in the comments, you are describing a dictionary:
A dictionary provides a mapping between two different values (also known as an associative array in other languages). You can declare one in Python like this:
mydict = {"hai": 2, "bye": 20}
print(mydict["hai"])
# 2
print(mydict["bye"])
# 20
You can then use variables as the key to access the dictionary:
mykey = "bye"
print(mydict[mykey])
# 20
For more details, please see the Python docs for dictionaries

If you don't go with dictionary and need to declare a variable name & value at runtime. We can achieve this with setattr()
Try this,
class Sample:
pass
obj = Sample()
x = 'hai'
setattr(obj, x, 20)
print(obj.hai)

Related

How to add character or a number to a variable in python? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I have some list like:
all0 = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all1 = [['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']]
And I want to print it out like
num = 0
print(all+num)
But it didn't work.
How to add a character or a number to a variable name?
Hmm, I am pretty sure that you do not need nor really want it, but Python has provision for computing a variable name. Simply it is a rather advanced feature and the normal way is to use mappings (dict) or sequence (list or tuple) containers.
Here, you would use:
all = []
all.append([['mortem' 'cliffi' 'gear' 'lerp' 'control']])
all.append([['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']])
num = 0
print(all[0])
BTW, this syntax is weird, because you are essentially concatenating adjacent litteral string...
But if you really, really need it you can build a interpolator of variables:
def getvar(name):
if name in locals():
return locals()[name]
elif name in globals():
return globals()[name]
else:
raise NameError(repr(name) + ' is not defined')
You can then do:
all0 = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all1 = [['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']]
num = 0
print(getvar("all%d" % num))
and get as expected:
[['mortemcliffigearlerpcontrol']]
You can use eval() for that.
eval('print(all{})'.format(num))
But this is really bad style. Don't do this. You should refactor your code and use for loops to go through your lists e.g.
all = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all.append(['video' 'player' 'stori' 'book' 'think' 'narr' 'kill'])
for l in all:
print(l)
Leaving aside how bad an idea it might be (probably really bad), variable names are just keys in a Python dict. A one-line solution might be:
vars()[new_name] = vars().pop(old_name)
for global variables, and
vars(some_obj)[new_name] = vars(some_obj).pop(old_name)
for variables of some_obj object.

Do stuff with variable that has the same name of a string [duplicate]

This question already has answers here:
How to use string value as a variable name in Python? [duplicate]
(3 answers)
How do I create variable variables?
(17 answers)
Closed 4 years ago.
let's say I have a variable called "x" and a string that has the value of "x" (string1 = "x"). How do I do stuff with the variable through the string?
For example change the variable's value or call a method if it's an object?
Thanks in advance
Variables are available through dictionaries locals() and globals(). If you want to access a particular variable by it's spring name, you can do e.g.
>>> my_var = 'hello'
>>> x = 'my_var'
>>> locals()[x]
'hello'
You can also assign back to the variable using this approach, e.g.
>>> my_var = 'hello'
>>> x = 'my_var'
>>> locals()[x] = 'something else'
>>> my_var
'something else'
Since functions are objects in Python, you can access any locally available functions in the same manner to call them.
>>> def my_test_function(n):
>>> return n*8
Accessing the method and calling it.
>>> locals()['my_test_function'](4)
32
For accessing attributes of objects by their name you can use getattr(), and setattr() to set them. For example, creating an object with a single property called your_prop.
class Example:
your_prop = 2
a = Example()
The value is available via your_prop.
>>> a.your_prop
2
The property can be accessed via name using getattr
>>> getattr(a, 'your_prop')
2
The property can be set using setattr:
>>> setattr(a, 'your_prop', 5)
>>> a.your_prop
5
Ok, let's suppose that you have lots of different functions: Aoo(), Boo(), Coo()... and let's suppose that you want to specify which of them to call via command line argument.
Now, that argument will be a string, so you need to call a function through its name, but you do not know in advance the name of the function.
One possible solution is to use exec():
def boo():
print("boo function")
def coo():
print("coo function")
Now:
argument = "boo"
exec(argument + "()")
>>> boo function
and
argument = "coo"
exec(argument + "()")
>>> coo function
It depends what you're trying to do, but you can scoop up whatever x is pointing to with locals() or globals():
def x(k):
return k + 1
string1 = "x"
the_function_x = locals()[string1]
print(the_function_x(3))
outputs 4 (it called the x function by utilizing string1).

How to assign a value to a variable given as parameter?

def function(x):
x = 4
variable = 0
function(variable)
print(variable)
This would output 0 but is there a way that it outputs 4? And also it should be without return.
First of all, I'd suggest you take a look to this nice explanation about python names and values. Now, one possible way to achieve what you want would be using a mutable structure as a dictionary, so you can pass your variable inside, something similar to this would do it:
def function(dct):
dct['variable'] = 4
dct = {
'variable': 0
}
function(dct)
print(dct['variable'])
More info can be found in python docs

Create variable name from two string in python [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed last year.
I am looking to create a variable name from two strings in Python, e.g.:
a = "column_number"
b = "_url1"
and then be able to get a variable name "column_number_url1" that I can use.
I appreciate this is in general not a good idea - there are numerous posts which go into why it is a bad idea (e.g. How do I create a variable number of variables? , Creating multiple variables ) - I mainly want to be able to do it because these are all variables which get defined elsewhere in the code, and want a easy way of being able to re-access them (i.e. rather than to create thousands of unique variables, which I agree a dictionary etc. would be better for).
As far as I can tell, the answers in the other posts I have found are all alternative ways of doing this, rather than how to create a variable name from two strings.
>>> a = "column_number"
>>> b = "_url1"
>>> x = 1234
>>> globals()[a + b] = x
>>> column_number_url1
1234
The reason that there aren't many posts explaining how to do this is because (as you might have gathered) it's not a good idea. I guarantee that your use case is no exception.
In case you didn't notice, globals() is essentially a dictionary of global variables. Which implies that you should be using a dictionary for this all along ;)
You can use a dictionary:
a = "column_number"
b = "_url1"
obj = {}
obj[a+b] = None
print obj #{"column_number_url1": None}
Alternatively, you could use eval, but remember to always watch yourself around usage of eval/exec:
a = "column_number"
b = "_url1"
exec(a+b+" = 0")
print column_number_url1 #0
eval is evil
As an alternative to Joel's answer, a dictionary would be much nicer:
a = "column_number"
b = "_url1"
data = {}
data[a+b] = 42

Is there a way to append an integer to the end of a variable name in python [duplicate]

This question already has answers here:
How to create an unknown amount of variables in python
(6 answers)
Closed 9 years ago.
after much googling i now ask. Is there a way to append an integer to the end of a variable name. Essentially creating a new variable with each iteration of a for loop. IE:
def parser(lst):
count = 0
for obj in lst:
if isinstance(obj,list):
parser(obj)
else:
for string in obj:
var+count = o
This is what i get when i try to run above code:
SyntaxError: can't assign to operator
You almost certainly want to use a list:
def parser(lst):
vars = []
for obj in data: # did you mean "for obj in lst:"?
if isinstance(obj,list):
parser(obj)
else:
for string in obj:
vars.append(o) # did you mean "vars.append(string)"?
Then, instead of, say, var5, you would use vars[5].
Doorknob of Snow's answer is correct, but for completeness, you can create a new variable using locals()[var + str(count)] = o. But this is a bad idea, so don't.

Categories

Resources