Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 535
user2757442 Avatar asked May 29 '26 21:05

user2757442


2 Answers

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.

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.

like image 31
Awalrod Avatar answered May 31 '26 09:05

Awalrod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!