Reputation: 113
For simplicity I'm try to do this.
spam = [1,2,3]
stuff = [spam]
x = input()
if x in stuff:
print(True)
else:
print(False)
As it runs:
>>> spam
False
Of course it doesn't print 'True' because the string 'spam' is not equal to the variable spam.
Is there a simple way of coding that I could check if the input is equal to the variable name? If not simple, anything?
Upvotes: 0
Views: 5127
Reputation: 4212
You should check the locals()
and globals()
dictionaries for the variable. These dictionaries have variable names as keys and their values.
spam = [1,2,3]
stuff = [spam]
x = raw_input()
if x in locals() and (locals()[x] in stuff) or \
x in globals() and (globals()[x] in stuff):
print(True)
else:
print(False)
You can read more on locals()
and globals()
.
Upvotes: 2
Reputation: 740
isnt better to use:
data = {'spam':[1,2,3]} #create dictionary with key:value
x = input() # get input
print(x in data) #print is key in dictionary (True/False) you might use:
#print(str(x in data)) #- this will convert boolean type name to string value
Upvotes: 0
Reputation: 29033
It's a weird idea to try and connect variable names with the world outside the program. How about:
data = {'spam':[1,2,3]}
stuff = [data['spam']]
x = raw_input()
if data[x] in stuff:
print(True)
else:
print(False)
Upvotes: 0