3

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user2757442
  • 165
  • 5
  • 12

2 Answers2

9

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.

Community
  • 1
  • 1
  • 2
    +1 What could be a better way to implement a ['dictionary'](http://en.wikipedia.org/wiki/Dictionary) than using a ['dictionary'](http://en.wikipedia.org/wiki/Associative_array)? – tobias_k Jun 20 '14 at 15:42
1

Adherent is a variable, and your first line sets the value to "a person who follows or upholds a leader, cause, etc.; supporter; follower."
word is also a variable, the value being provided by the user.
print() prints the value that a variable stores. If you want the user to be able to select a word to define you'll need a dictionary of words.

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

The first value ("Adherent") is the key. It is associated with the second string.
A dictionary works like and list except in a list values are accessed by their index. In a dictionary values are accessed by their key.

So:

words = {
 "Adherent": "a person who follows or upholds a leader, cause, etc.; supporter; follower.",
}
word = raw_input("Word: ")
print words[word] #this is equivalent to words["Adherent"] if the user inputs "Adherent"

Just a sidenote, objects and variables generally should start with lowercase letters.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
Awalrod
  • 268
  • 1
  • 4
  • 14