Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help! Functions
#1
Hi everyone! I am trying to create an English Thesaurus which the user is going to write an word as input and get the corresponding meaning, also if the user inputs a non-existing word than program has to output the variable m.
Unfortunately my code outputs m either way.
I'll be appriciated any help of you, thanks.
import json
data = json.load(open("data.json"))

def dictioanry(inp):
    m = "The word doesn't exist. Please double check it."
    for k in data.keys():
            if inp != k:
                return m
            else:
                answer = data[k]
                return answer

    
print(dictioanry(inp = input("Enter Word: "))) 
Output:
Enter Word: rain The word doesn't exist. Please double check it.
And this is what corresponds to rain in data:
Output:
>>> data["rain"] ['Precipitation in the form of liquid water drops with diameters greater than 0.5 millimetres.', 'To fall from the clouds in drops of water.']
Reply
#2
At line 6, you're looping over the keys in the dictionary (which if it's a recent version of python will return the keys in the same order they were created).

When the loop starts, you then check the input against that first key and return success or failure. So the loop never continues and you never check any more keys.

If you want to loop over all the keys, you'd need to avoid returning on failure, but wait until the loop finishes.

Instead of looping over it you can ask if the key exists in the dictionary already.

if inp in data:
    # key exists already print definition.
    ...
else:
    # key not in dictionary.  Whine.
    ...
Reply
#3
Was it easy like that! Thank you, I appreciate it.
Reply
#4
no need to check the key exists, just use dict.get() method

import json
 
def meaning(word, dictionary):
    return dictionary.get(word, "The word doesn't exist. Please double check it.")

with open("data.json") as f:
    dictionary = json.load(f)
word = input("Enter Word: ")
print(meaning(word, dictionary))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020