Search code examples
pythonvariablesraw-input

How to use raw input to define a variable


Here is my code:

Adherent = "a person who follows or upholds a leader, cause, etc.; supporter; follower."

word=raw_input("Enter a word: ")

print word

When I run this code and input Adherent, the word Adherent is produced. How can I have the definition of Adherent pop up instead?


Solution

  • You can (should) use a dictionary where words are mapped to definitions:

    >>> word_dct = {"Adherent" : "a person who follows or upholds a leader, cause, etc.; supporter; follower."}
    >>> word=raw_input("Enter a word: ")
    Enter a word: Adherent
    >>> word_dct[word]
    'a person who follows or upholds a leader, cause, etc.; supporter; follower.'
    >>>
    

    Creating dynamic variables is a bad and potentially dangerous practice. Not only is it very easy to lose track of them, but if you use exec or eval to create them, you run the risk of executing arbitrary code. See Why should exec() and eval() be avoided? for more information. Even accessing locals or globals is generally frowned upon in favor of using a list or dictionary.