Reputation: 764
I have fixed variables :
apple_weight = 50
mango_weight = 100
veggie1 = apple
veggie2 = mango
I want to be able to refer the weight variables by using the veggie variables in my code :
whatcomeshere = globals()[[str(veggie1) + str(_weight)]]
print("The weight of the veggie {}, is {}").format(veggie1, whatcomeshere)
I am trying to use the globals statement as above but get the following error:
Traceback (most recent call last):
File "<ipython-input-9-bceaa9070b38>", line 3, in <module>
veggie1 = apple
NameError: name 'apple' is not defined
Upvotes: 0
Views: 39
Reputation: 1403
The error you are receiving is because the name apple
is not declared or defined before referencing it in the line veggie1
. I assume you want veggie1
to be the string apple so you would need to
veggie1 = "apple"
For the issue of refering to other variables, you can't directly build the names of variables like you are in
[str(veggie1) + str(_weight)]
Edit: skullgoblet1089's Answer shows a good way to use a dictionary to do what you are doing
What this will return is [apple50]
which is I presume is not what you want. You need to explicitly call apple_weight
.
If you want to generate variable names you would want to use a dictionary and then generate strings as keys for the dictionary.
https://www.w3schools.com/python/python_dictionaries.asp
Upvotes: 0
Reputation: 614
apple
and mango
are interpreted as variables that do not exist. You mean to define them as string literals. See below:
apple_weight = 50
mango_weight = 100
veggie1 = 'apple'
veggie2 = 'mango'
You might find it easier to use a simple data type like a dictionary to encapsulate this structure rather than finagling the global namespace.
APPLE_CDE = 'apple'
MANGO_CDE = 'mango'
d = {
APPLE_CDE: {'weight': 50},
MANGO_CDE: {'weight': 100}
}
w = d.get(APPLE_CDE, {}).get('weight', None)
print(w)
Upvotes: 2