Python - NameError: name 'search_fixture' is not defined - python

I am making a program here and I get the error. How to fix it as I have defined the function but it says I haven't?
Traceback (most recent call last):
File "G:/Practice Program/Task3 Practice/Task3_Own_copy.py", line 19, in <module>
menu()
File "G:/Practice Program/Task3 Practice/Task3_Own_copy.py", line 9, in menu
search_fixture()
NameError: name 'search_fixture' is not defined
def menu():
print("\n\nWelcome to the fixture manager")
print("\nWould you like to:\n\nOption A\tSearch for a fixture\nOption B\tOutstanding fixtures"
"\nOption C\tDisplay leader board\n\nEnter Q to quit\n\nPlease enter A,B,C, or Q\n")
choice = input(">>>").upper()
if choice == "A":
search_fixture()
elif choice == "B":
print("Yolo")
elif choice == "C":
print("Yolo")
elif choice == "Q":
print("\nThank you for using the tracker program, goodbye.\n")
quit()
else:
menu()
menu()
def search_fixture():
found = False
search = input("\n\nPlease enter a fixture number:")
with open("firesideFixtures.txt","r") as f:
for line in f:
fixtureNumber,fixtureDate,fixtureTime,player1Nickname,player2Nickname,fixturePlayed,winningNickname = line.split(",")
if fixtureNumber.upper() == search.upper():
found = True
print("\nFixutre Number:",fixtureNumber,"\nFixture Date:",fixtureDate,
"\nFixture Time:",fixtureTime,"\nPlayer 1 Nickname:",
player1Nickname,"\nPlayer 2 Nickname:",player2Nickname,
"\nFixture Played:",fixturePlayed,"\nWinning Nickname:"
,winningNickname,"\n")
if found == False:
print("\n There were no results for:",search,". Please search for another fixture")
search_fixture()
search_fixture()

Assuming the indentation is correct as you stated, the problem is the way the Python interprets the file. It defines the functions as it reads them. In your case, it's trying to access the search_fixture() function, but it hasn't gotten to it yet, so it's not defined.
Swap the order of the functions, and your problem should be solved. I tried copying and pasting your code, reproduced the problem, moved the search_fixture definition so it was before Menu, and it worked.

Python (and most other languages) execute from top to bottom. If you are defining FunctionA ( that is calling another FunctionB that hasnt been defined yet) and then calling the FunctionA, you are attempting to call FunctionB indirectly, which hasnt been defined.
This is what you are doing:
def FunctionA():
FunctionB()
FunctionA()
def FunctionB():
print("inside of B")
FunctionB()
This will cause the error because from top to bottom, it doesn't know what FunctionB() is by the time it gets to it because it hasn't been defined yet.
Typically single file python programs are going to define all of the functions first, and then call them.
Something like this is what you want:
def FunctionA():
FunctionB()
def FunctionB():
print("inside of B")
FunctionA()
FunctionB()

Related

Unsure on how to call this function within another function - Python

really sorry if someone has asked this before, i just couldn't find what i was looking for, I'm new to coding and aren't sure why i cant get 'matrice2x2mult' function to be called within 'runcalc'. However i suspect it is to do with me calling the function 'runcalc' at the bottom. Any help will be greatly appreciated. Once again sorry.
-I get the error message:
Traceback (most recent call last):
File "FILE_PATH", line 42, in <module>
query.runcalc(q)
File "FILE_PATH", line 19, in runcalc
matrice2x2mult()
NameError: name 'matrice2x2mult' is not defined
import time
class calculator():
def __init__(self, method):
self.method = method
def matrice2x2mult():
print("Matrix 1:")
a = input("a:")
b = input("b:")
c = input("c:")
d = input("d:")
print(f"({a} {b})\n({c} {d})")
def runcalc(self, method):
if self.method == "1":
print("yes")
matrice2x2mult()
elif self.method == "2":
pass
print ("welcome to matrice Calculator: \nEnter 'HELP' for help menu")
time.sleep(1)
q = input(r"What method is required:")
q = str(q)
help1 = False
while help1 == False:
if r"HELP" in str(q):
print("------help-menu------")
print("ENTER '1' FOR 2X2 MATRIX MULTIPLICATION")
print("ENTER '2' FOR A INVERSE OF A 2X2 MATRIX")
time.sleep(1)
q = str(input(r"What method is required:"))
break
else:
break
pass
query = calculator(q)
query.runcalc(q)```
[1]: https://i.stack.imgur.com/s6jud.png
Since matrice2x2mult is defined within calculator, and you're trying to access it via runcalc which is also defined within the same class, you need to use self.matrice2x2mult to access the function. The only way that using just matrice2x2mult would work is either if it was defined in global scope rather than just in that class, or if you did something like matrice2x2mult = self.matrice2x2mult which would be weird and not recommended.

missing one required positional argument

I was working on a blockchain project. Nothing wrong seemed to come of it, until I added the mining function. Then it spit out two errors that it was missing positional argument. the first was the main function on line 45, and the second one was that if name is main function. which makes since. It had to do with the mining function. The code is a bit lengthy and hard to understand so I am keeping the necessary parts.
from hashlib import sha3_512
##some hashing stuff
class Block():
## the variables thrown into the function
def __init__(self, txdata, number):
#initialize function.
# More hashing stuff
class blockchain:
difficulty = 4
def __init__(self, chain=[]):
#Initialize function. Sets up the blockchain
def add(self,Block):
#lables adding stuff to the chain
def mine(self,Block):
try:
block.prev = self.chain[-1].get('hash')
except IndexError:
pass
while True:
if Block.hash()[:blockchain.difficulty] == "0"*blockchain.difficulty:
self.add(Block)
break
else:
Block.nonce +=1
def main():
blockchain()
bchain = ["Nice day stack overflow", "Once again I need help with my bad code"]
Num = 0
for txdata in bchain:
Num += 1
blockchain.mine(Block(Block.txdata, Num)) #the error popped up here. I don't get it. I tried fiddling around with it, nothing.
if __name__ == '__main__':
main()
Can you help me solve this error. It could ruin the entire project if not fixed.
Error
Traceback(most recent call last)
File "blockchain.py", line 47 in <module>
main()
File "blockchain.py", line 45, in main()
blockchain.mine(Block(Block.txdata, Num))
Type error: mine missing one positional argument: Block
You need to keep hold of the instance of blockchain().
def main():
b = blockchain() # keep hold of the instance in b
bchain = ["Nice day stack overflow", "Once again I need help with my bad code"]
Num = 0
for txdata in bchain:
Num += 1
b.mine(Block(Block.txdata, Num)) # Use the instance here
if __name__ == '__main__':
main()

How to call an action from def function - Python

I have python code as below
def call():
input1 = input('Bot1:')
input2 = input('Bot2:')
call()
input1
How to call 'input1' action only. I want after call it, the input1 action will start for inputting data on the screen.
But on above code... when I run, it show warning 'input1 not defined'
Thanks you!
You can't access the local variables of a function from outside of it. One way to workaround that limitation would be to do something like this:
ACTION1, ACTION2 = 1, 2
def get_input(action):
if action == ACTION1:
return input('Bot1:')
elif action == ACTION2:
return input('Bot2:')
else:
raise RuntimeError('Unknown action')
input1 = get_input(ACTION1)

ValuError using import function in class

I'm sure there's a simple explanation for this (beyond just that I'm new to Python), but let's say I have two file in the same directory. One is this little script in a file named lexicon.py that checks user input:
def string_checker3(action):
try:
check = isinstance(action, basestring)
if check:
return True
else:
raise ValueError
except ValueError:
print "We need a string here!"
return None
def Chipcar_testgreeting(action):
action_split = action.split()
for i in action_split:
strcheck = string_checker3(action)
if strcheck == None:
StartGame
else:
pass
The other script, my main script, is called newGame.py and has a class like this, within which I would like to call the Chipcar_testgreeting(action) function.
from lexicon import *
class ChipCar(Scene):
def enter(self):
print "What's up mothafucka! Get in the Bran Muffin car!"
action = raw_input("> ")
user_test = lexicon.Chipcar_testgreeting(action)
user_test
if(action == "shut up chip" or action == "oh no, it's chip"):
print "forget you!"
print action
return next_scene('Your_death')
#return 'Death'
elif(action == "hi chip" or action == "hello chip"):
print "What's up?!?! Let's go to O&A..."
return next_scene('Chip_in_studio')
else:
print "what's wrong with ya are ya stupid or sumptin? Let's go to my mudda's house, I think Lamar's there..."
return next_scene('Chip_mom_house')
FirstScene = ChipCar()
StartGame = FirstScene.enter()
However, I get this error now:
user_test = lexicon.Chipcar_testgreeting(action)
NameError: global name 'lexicon' is not defined
What am I doing wrong?
As you wrote from lexicon import *, all the importable names from that module are available to you directly (in other words, you don't need lexicon. anymore).
If you write import lexicon, now you have only imported the lexicon name into your module, and you need to use it and the scope-resolution operator (that's the .) to get to the other names of objects inside that module. In this case, you can use lexicon.Chipcar_testgreeting(action).
So, either replace from lexicon import * with import lexicon, or change lexicon.Chipcar_testgreeting(action) to Chipchar_testgreeting(action).
The recommended option is to use import lexicon.
Once you sort that out, you need to resolve another major issue which is this:
if strcheck == None:
StartGame
else:
pass
Not sure what do you expect StartGame to do here, since there is nothing with this name in the lexicon.py module.

Python: creating a temporary name for a specific function

I'm learning Python. I'm reading some code containing something like this:
class Menu:
'''Display a menu and respond to choices when run.'''
def __init__(self):
self.notebook = Notebook()
self.choices = {
"1": self.show_notes,
"2": self.search_notes,
"3": self.add_note,
"4": self.modify_note,
"5": self.quit
}
def display_menu(self):
print("""
Notebook Menu
1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit
""")
def run(self):
"""Display the menu and respond to choices."""
while True:
self.display_menu()
choice = input("Enter an option: ")
action = self.choice.get(choice)
if action:
action()
else:
print("{0} is not a valid choice".format(choice))
def show_notes(self):
pass
def search_notes(self):
pass
def add_note(self):
pass
def modify_note(self):
pass
def quit(self):
pass
There are some lines very interesting:
action = self.choice.get(choice)
if action:
action()
Seems it's creating a temporary name for a specific function.
So I did the following test for it to learn more:
>>> def show_notes():
print("show notes")
>>> def search_notes():
print("search notes")
>>> choice = {"1": show_notes, "2": search_notes}
>>> action = choice.get(1)
>>> action()
But I get the following error:
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
action()
TypeError: 'NoneType' object is not callable
Can someone tell me what the technique is and what principle is behind?
Functions are first class objects, and you can create additional references to them. These are just as temporary as you need to them to be, but they can be permanent too.
Your own attempt confused strings and integers however; you used 1 (an integer) where the actual key is '1' (a string). Because you used the wrong key, the dict.get() method returned a default instead, None. None is not a function object and the call fails.
Had you used the right key your code would have worked too:
>>> def show_notes():
... print("show notes")
...
>>> def search_notes():
... print("search notes")
...
>>> choice = {"1": show_notes, "2": search_notes}
>>> choice['1']
<function show_notes at 0x10b1fae18>
>>> choice['1']()
show notes
You can make use of dict.get() returning a default here too, by giving the method a better default to return:
>>> choice.get('none-such-key', search_notes)()
search notes
It seems there's an error in your test. You should be getting "1" and not 1. Getting 1 is returning None because there's nothing defined for key 1. Therefore when you call it like a function it's not valid.
To clarify, "1" is a string and 1 is an integer, which are different keys.
Example:
>>> a = {"1": "yes"}
>>> a.get(1)
>>> a.get("1")
'yes'
Example II (using function):
>>> def hello():
... print "hello"
...
>>> hello()
hello
>>> a = {"1": hello}
>>> b = a.get(1)
>>> b()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>> b = a.get("1")
>>> b()
hello
It's not creating a random name for a function. The class method choice is selecting a function and returning it, and it is subsequently being assigned to the variable action. The function is then called by calling action, like you would any function.
Here's an example:
def foo():
print(5)
def getFunction():
return foo
x = getFunction()
x()
The output from this will be 5.
Taking a step back from all of this, you can assign any object to any variable. So consider the following example (I think this will help you understand a little bit more):
def foo():
print(5)
bar = foo
foo = 5
foo()
This will produce an error along the lines of integer objects are not callable. The way this works is that the function object contained in foo is being assigned to variable bar, and the integer 5 is being assigned to foo. The function hasn't changed, but the variable containing it has.
The very first part of defining a function def foo is letting the interpreter know that you are defining a function object and storing in the variable foo. The name and the mechanics of the function are separate.
Does this make sense?

Categories