This is my code block
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
elif len(get_close_matches(words, definitions.keys())) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus[get_close_matches(words, definitions.keys())]
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))
I expected to receive the meaning of the word "Grief". However, I kept receiving the error : function object is not subscriptable.
Here is the terminal log, just in case it might help:
My-MacBook-Pro:Python Adwok$ python3 dictionary.py
Look Up: GRERFAG
Did you mean grief instead? Enter 'Y' if yes or 'N' if no: Y
Traceback (most recent call last):
File "dictionary.py", line 22, in <module>
print(thesaurus(words))
File "dictionary.py", line 13, in thesaurus
return thesaurus[get_close_matches(words, definitions.keys())]
TypeError: 'function' object is not subscriptable
Please point out even the smallest details, I would appreciate that very much.
As stated by the error stack, in line 13 you are accessing thesaurus as if it was a list/dictionary (or any subscriptable object). Since thesaurus is a function (which is not subscriptable), you get an error. Thus, you need to invoke the function (instead of accessing it):
thesaurus(get_close_matches(words, definitions.keys()))
Also, you should notice:
At the end of your code you are correctly invoking the thesaurus function by calling print(thesaurus(words))
Consider reusing the result of get_close_matches to avoid multiple calls to the same function (which can lead to performance degradation if the call is resource consuming).
I suggest you the following solution:
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
else:
close_matches = get_close_matches(words, definitions.keys())
if len(close_matches) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus(close_matches)
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))
Related
**Getting error but confused why everything seems to be in place as it should be?**
why Am I getting the error please explain everything works from top to bottom basically till it hits that function and then that’s when it gives me that error that I am trying to figure out Because all my if an elif and else statement seems to be in order and working properly
import random
import emoji
def decor(write):
def wrap():
print(“Choose a decision!” + “\U0001F604")
write()
print("-Testing mode-")
return wrap()
def print_text():
print("mini project")
decorated = decor(print_text)
print("")
decision = input("please enter decision: " + "")
if decision == ("Right answer"):
decision = input("I will go to work today!: "+"\U0001F600")
elif decision ==("Wrong answer"):
decision = input("Will not go to work today: "+ "\U0001F612")
else:
print("Invalid answer try again!")
if decision == ("Wrong answer"):
decision = input("But in a bad mood: ")
elif decision ==("Right answer"):
decision = input("Your check will come out bigger cause you put in more hours: ")
print(decision)
else:
print("Invalid answer try again!")
Here is where I am getting the error
def Decision_maker():
x = lambda x: x*2 + 1
if x > 4:
decision = ("Right answer")
decision == input("You got a raise!")
if decision == ("Wrong answer"):
decision = input("You got fired: ")
Decision_maker()
Here is the error
> Traceback (most recent call last): File
> "/private/var/mobile/Containers/Shared/AppGroup/3EBFD0C8-D5AE-4513-B2E3-6C38570AE9F0/Pythonista3/Documents/site-packages-3/decision maker.py", line 60, in <module>
> Decision_maker() File "/private/var/mobile/Containers/Shared/AppGroup/3EBFD0C8-D5AE-4513-B2E3-6C38570AE9F0/Pythonista3/Documents/site-packages-3/decision maker.py", line 49, in Decision_maker
> if x > 4: TypeError: '>' not supported between instances of 'function' and 'int
The problem is here:
x = lambda x: x*2 + 1
if x > 4:
You're passing your function rather than the result of your function. Instead try:
y = lambda x: x*2 + 1
if y(value) > 4:
Where value is whatever you want to pass into your function. By writing "lambda x:" you're creating an anonymous function with the argument "x".
Why am I getting this error and how can I fix this?
import json
from difflib import SequenceMatcher
from difflib import get_close_matches
data = json.load(open("data.json"))
def translate(word):
match = get_close_matches(word,data.keys(),cutoff=0.8)
if word.lower() in data:
return data[word.lower()]
elif len(match) > 1:
yn = input("Did you mean %s? Enter y or n" %match[0])
else:
return "Not in the dictionary. Please check again."
input = input("What is your word? ")
print(translate(input))`
What is your word? caca
Traceback (most recent call last):
File "dictionary.py", line 18, in <module>
print(translate(input))
File "dictionary.py", line 12, in translate
yn = input("Did you mean %s? Enter y or n" %match[0])
TypeError: 'str' object is not callable
a python beginner here. My previous programming experience is with basic in the eighties, and logic programming in a proprietary system, neither of which is much help for learning python. So, to my question:
I'm writing a math quiz program (just for learning), and I've made a "main menu" by defining a function block; within it, if input is a then another func addition() is called, if input is s then func subtraction() is called and this works as intended. Within those function blocks, I'm setting a global variable quiztype to name of that function. Then I call yet another function again() from within those, to query if user wants another question of the same sort, if yes, I try to return to the relevant function with quiztype () and this fails with TypeError: 'str' object is not callable.
I did find some seemingly-related topics but either couldn't implement the answers or didn't even understand what they were talking about as I'm a beginner.
What options do I have for returning to the previously executed function?
Here's the code: (notice that variable names are not what above - different language)
from random import randint
def Alku ():
kysy = True
while kysy:
lasku = input('Yhteen, Vähennys, Lopeta? ')
if lasku == 'y':
Yhteenlasku ()
kysy = False
elif lasku == 'l':
break
kysy = False
def Uudestaan ():
kysy = True
while kysy:
samauudestaan = input('uudestaan? (k/e)? ')
if samauudestaan == 'k':
Lasku()
kysy = False
elif samauudestaan == 'e':
Alku ()
kysy = False
def Yhteenlasku ():
global Lasku
Lasku='Yhteenlasku'
n1=(randint(1,10))
n2=(randint(1,10))
a1=n1+n2
print(n1, end="")
print(" + ", end="")
print (n2, end="")
print(" = ", end="")
a2=int(input())
print()
if a1==a2:
print('oikein!')
elif a1!=a2:
print('väärin!')
Uudestaan()
Alku ()
And what is returned in terminal:
Traceback (most recent call last):
File "laskut2.py", line 43, in <module>
Alku ()
File "laskut2.py", line 8, in Alku
Yhteenlasku ()
File "laskut2.py", line 41, in Yhteenlasku
Uudestaan()
File "laskut2.py", line 19, in Uudestaan
Lasku()
TypeError: 'str' object is not callable
Your code is fine as it stands, although your global declaration is in an odd place. Still, remove the inverted comma's around your definition of Lasku which is defining it as a string and it will work.
global Lasku
Lasku=Yhteenlasku
P.S. Welcome back to programming!
In response to your question, globals would normally be declared at the beginning of your code or when the data to define becomes available but in this case you are defining it as a function, so you can't define it until the function has been defined. I guess as long as it works, where it is is fine. Personally, in this case, I'd define it here:
global Lasku
Lasku=Yhteenlasku
Alku ()
We really need to see your code to see what you want to achieve but from the sound of it you want to do something like this. From the question it look like you will be recalling function within functions and returning functions, creating recursions which is not that pythonic and also will eventually throw errors and the other is not really needed in this situation. jedruniu has put really quite a good explanation on function variable assignment too.
Less robust version:
def addition():
pass # Put code here
def subtraction():
pass # Put code here
def menu():
while True:
cmd = input("Addition or subtraction? (a/s): ")
if cmd == "a":
addition()
elif cmd == "s":
subtraction()
menu()
Other version (w/ score):
def addition():
# Put code here
result = True
return result # Will be added to score, so any integer or True/False
def subtraction():
# Put code here
result = True
return result # Will be added to score, so any integer or True/False
def menu():
score = 0
while True:
cmd = input("Addition or subtraction? (a/s/exit): ").strip().lower()
if cmd == "exit":
break
elif cmd == "a":
score += addition()
elif cmd == "s":
score += subtraction()
else:
print("Unknown option...")
# Do something with score or return score
if __main__ == "__main__":
menu()
You can assign function to a variable (because function is in Python first-class citizen), so effectively, for example:
def fun1():
print("fun1")
def fun2():
print("fun2")
def fun3():
print("fun3")
f1 = fun1
f2 = fun2
f3 = fun3
functions = {
"invoke_f1" : f1,
"invoke_f2" : f2,
"invoke_f3" : f3
}
functions["invoke_f1"]()
function_to_invoke = functions["invoke_f2"]
function_to_invoke()
yields:
fun1
fun2
More reading: https://en.wikipedia.org/wiki/First-class_function
In your specific example, modify your Uudestaan function.
def Uudestaan ():
Lasku = Yhteenlasku #Add this line
kysy = True
while kysy:
samauudestaan = input('uudestaan? (k/e)? ')
if samauudestaan == 'k':
Lasku()
kysy = False
elif samauudestaan == 'e':
Alku ()
kysy = False
because you were trying to invoke string, and this is not possible. Try to invoke type(Lasku) in your case and you'll see that it is of type str. Invoke it in function with my modification and you'll see type of function.
However I am not sure what is going on in this code, is this finnish? swedish?
I have no experience with python, so I thought I'd start looking into it for my new hobby. I'm having an issue when it comes to a switch case, which python doesn't have, after googling I found most use a dictionary style method which you can see below. It's a small .py file I'm building to replicate an ATM style system, just to get me familiar with all of python's options.
while True:
print ("Who are you?")
name = input().lower()
if re.match("^[A-Za-z]*$", name):
break
else:
print('Please enter a valid name')
print('Hello ' + name)
print("Please enter your PIN " + name)
pin = input()
accounts = {"stephen" : stephen,
"Dean" : Dean,
"Jennifer" : Jennifer,
"Liam" : Liam,
"Billie" : Billie,
"Decky" : Decky,
"Joel" : Joel,
}
accounts[name]()
def stephen():
if pin == 1234:
print("Pin Accepted")
else:
print("Wrong PIN")
def Dean():
if pin == 1344:
print("Pin Accepted")
else:
print("Wrong PIN")
Now the problem is that when I get to the enter pin section, it comes back with an error saying the following:
options = {"stephen" : stephen, NameError: name 'stephen' is not defined
Any ideas what it could be? looking at the example it seems I have everything right, but I couldn't find an answer from googling the specific error.
At the point where you get the error because you try to use stephen, it's not defined yet. Create that dictionary after the function has been defined.
Python is an interpreted language, which means that the code is executed by the interpreter line by line without previously compiling. So the function stephen is not defined when you try to enter it into the dictionary because it's only defined later in the script. Define the function stephen prior to entering it into the dictionary and your script will work.
accounts = {"stephen" : stephen,
"Dean" : Dean,
"Jennifer" : Jennifer,
"Liam" : Liam,
"Billie" : Billie,
"Decky" : Decky,
"Joel" : Joel,
}
1) the values in your accounts dictionary cause the error. no matter variables or functions, you have to define them before use.
2) remove the last comma in your account dictionary
An easy sample is here:
>>> mydict ={"a":A} # A is not defined, will raise Error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined
>>> mydict ={"a":"A"} # A is string here, it is okay
>>> A = "A" # declares A and assigns value to it
>>> mydict ={"a":A} # good now.
i'm not sure how to go about this...
I want to use import to go to another script (Once it's called, the original script has finished) but I need the second script to print a variable from the original.
So, I can import the second script and use the prints fine, however if I try and import the original script so I can access the variable..
But if I do that, it just gives me an error:
Traceback (most recent call last):
File "C:\Users\luke\Desktop\k\startGame.py", line 2, in <module>
import Storyline
File "C:\Users\luke\Desktop\k\Storyline.py", line 1, in <module>
import startGame
File "C:\Users\luke\Desktop\k\startGame.py", line 56, in <module>
Storyline.startGame1()
AttributeError: 'module' object has no attribute 'startGame1'
I am trying to print this:
print ("I see you have picked " + startGame.currentPokemon)
and I am calling it like this:
Storyline.startGame1()
and the currentPokemon is
currentPokemon = inputKK
(InputKK is an input of the starter pokemon)
Is there any way to do this? And yes, i'm making a pokemon game in Python, but it's a version that isn't using real pokemon names..
Storyline script:
import startGame
def startGame1():
print ("Welcome to the H.Q of I.O.D")
print ("I am Professor Steel.")
print ("I see you have picked " + startGame.currentPokemon)
startGame script:
import Storyline
inputKK = input("Choose from, 'Craigby', 'Robinby' or 'KKby' ")
if(inputKK == "Craigby"):
print("Craigby is a electric type.")
print("Craigby: Attack = 7, Defence = 3, Health = 6, Speed = 12")
if(inputKK == "Robinby"):
print("Robinby is a fire type.")
print("Robinby: Attack = 6, Defence = 5, Health = 7, Speed = 7")
if(inputKK == "KKby"):
print("KKby is a water type.")
print("KKby: Attack = 5, Defence = 8, Health = 11, Speed = 5")
print("")
os.system('cls')
currentPokemon = inputKK
counter = 0;
while(counter < 1):
print("Welcome to pokeby.")
print("Type S for [STORYLINE]")
print("Type R for pokemon in the field [CURRENT IS GRASS] ")
print("Type Q for [QUIT]")
inputMainMenu = input("S/R/Q ...")
if(inputMainMenu == "S"):
os.system('cls')
counter = counter + 2
Storyline.startGame1()
if(inputMainMenu == "R"):
os.system('cls')
counter = counter + 2
if(inputMainMenu == "Q"):
os.system('cls')
inputExit = input("Are you sure you want to quit? Y/N ")
if(inputExit == "Y" or inputExit == "y"):
print("K")
else:
counter = counter + 1
Don't import StartGame in your Storyline script. Instead, just pass the desired value to your StartGame1 function.
# Storyline.py
def startGame1(currentPokemon):
print ("Welcome to the H.Q of I.O.D")
print ("I am Professor Steel.")
print ("I see you have picked ", currentPokemon)
Then in startGame you call Storyline.startGame1(inputKK) passing the name of the Pokemon.
BTW, it's a little confusing that your startGame1 function isn't in the module startGame...
You are trying to import Storyline into startGame, and also trying to import startGame into Storyline. You just can't do this kind of recursive import. While importing startGame, Storyline is coming across your Storyline.startGame1() call before startGame1() has been defined, so you get the no attribute error.
You should restructure your files so that this becomes unnecessary.
[edit: don't listen to me; it was late and I didn't think hard enough about what I was saying.]
You can't reference attributes or methods in a module like that. What you need is to put your methods in a class. Alternatively, I think you could do from Storyline import startGame1(). But really, use classes [if you want to]; [i think] they are good. Python docs on classes here.