Unsure on how to call this function within another function - Python - 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.

Related

Why is the return function not passing the variables to the next function?

I'm trying to get rid of the error without moving the input function out of the userInput function. I expected the return function to remove the NameError. I looked all over stack exchange and in my textbook to figure out this problem.
def userInput():
a = float(input("Enter a: "))
b = float(input("Enter b: "))
return (a,b)
def printFunction(a2,b2):
print(a2)
print(b2)
def main():
userInput()
printFunction(a2,b2)
main()
NameError: name 'a2' is not defined
Functions return values, not variables. The names a and b are only defined in userInput: you need to receive the values returned by userInput in variables defined in main.
def main():
x, y = userInput()
Printfunction(x, y)
You need to assign the return values of userInput to variables if you want to be able to refer to them on the next line:
def main():
a2, b2 = userInput()
Printfunction(a2,b2)
or you could skip a step and pass userInput's output directly to Printfunction as positional arguments with the * operator:
def main():
Printfunction(*userInput())

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)

Using parameters to pass values between functions

I am currently having an issue, as i am relatively new to python , it might be a very easy solution for others.
I want to pass a parameter between both functions 'eg1' and 'eg2', there is a common number the user will input (example:10) then 'eg1' will add 1 to it and 'eg2' will take the final value of 'eg1' and add 1 more to it, (example: 10 will become 11 then 12)
It is troubling me because this keeps popping up:
Traceback (most recent call last):
File "example.py", line 69, in <module>
eg2(a)
File "example.py", line 63, in eg2
b = a.d
AttributeError: 'int' object has no attribute 'd'
I can't seem to find my mistake.
class Helper:pass
a = Helper()
def one(a):
d = a
d += 1
print d
def two(a):
b = a.d
b += 1
print b
print
print ("Please enter a number.")
a = int(input('>> ')
print
one(a)
print
two(a)
Reference for parameter passing:
Python definition function parameter passing
'Print' with nothing means to leave an empty line, for me
I messed up the title, fixed.
Since you are already using a class, you can pass the number you want to increment twice as an instance attribute, and call your increment functions on that attribute. This will avoid passing the updated value after calling one in the method two
Calling one and then two makes sure that two is working on the updated value after calling one.
class Helper:
# Pass num as parameter
def __init__(self, num):
self.num = num
# Increment num
def one(self):
self.num += 1
# Increment num
def two(self):
self.num += 1
h = Helper(10)
h.one()
print(h.num) # 11
h.two()
print(h.num) # 12
Based on your comments, here's one way to get the result. I am using python3:
class Helper:
d = None
cl = Helper()
def one(a):
cl.d = a
cl.d += 1
return cl.d
def two():
cl.d += 1
return cl.d
print ("Please enter a number.")
a = int(input('>> '))
print(one(a))
print(two())

Python - NameError: name 'search_fixture' is not defined

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()

How do I transfer varibles through functions in Python

I am trying to read from keyboard a number and validate it
This is what I have but it doesn't work.
No error but it doesn't remember the number I introduced
def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
def read():
a=input("Nr: ")
while (IsInteger(a)!=True):
a=input("Give a number: ")
a=0
read()
print(a)
I think this is what you are trying to achieve.
def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
def read():
global a
a=input("Nr: ")
while (IsInteger(a)!=True):
a=input("Give a number: ")
a=0
read()
print(a)
You need to use global expression in order to overwrite the global variable without a need to create return inside the function and typing a = read().
But I would highly recommend u to use the return and re-assigned the value of 'a', as someone stated below.
a is a local variable to the two functions and isn't visible to the rest of your code as is. The best way to fix your code is by returning a from your read() function. Also, the spacing is off in your IsInteger() function.
def IsInteger(b):
try:
b=int(b)
return True
except ValueError:
return False
def read():
a=input("Nr: ")
while not IsInteger(a):
a=input("Give a number: ")
return a
c = read()
print(c)
It appears as though you are not returning the result of the read() function.
The last line of your read function should be "return a"
And then when you call the read function you would say "a = read()"

Categories