So here is the the problem
def func_1(x):
print 'function'
def func_2(x,y):
print 'function2'
def func_3():
n=func_1(x)
m=func_2(x,y)
i have 2 functions and i have a third one which needs to use the first 2 , the problem is that i don't know how to make it work . I give the arguments of the first two functions and it gives me an error , tried giving the functions as an argument , but it gives me a syntax error
i also tried of getting rid of the first function , solving the problem with a while cycle like this
counter = 0
while counter<10:
n=func_1(x)
m=func_2(x,y)
but it tells me that tuple object is not callable
If someone could tell me how to do it without defining the first 2 functions inside the third one i would be grateful
You are not passing func_3() any arguments, and still expecting it to know x and y
Also func_1 () and func_2 doen't return anything, so there is no need to do value = func() at func_3()
Try this:
def func_1(x):
print "i'm func1"
print x
def func_2(x,y):
print "i'm func2"
print x, y
def func_3(x, y):
func_1(x)
func_2(x, y)
func_3(1, 2)
It's hard to tell from your question, but it sounds like you are trying to get func3 to use functions passed as arguments? Something like
def func1(x):
return 2*x
def func2(x, y):
return 3*x + 2*y
def func3(x, y, fn1, fn2):
return fn1(x) + fn2(x, y)
def main():
print(5, 8, func1, func2)
if __name__=="__main__":
main()
Related
A python wrapper specifically for for-loops and its actions
I write a lot FOR loops that are, well, pretty generic.
For eg:
for x in y:
do something
... and error-prone. eg forgetting the ":", or indentation probs.
Could we put the FOR loop in a def, and call it, supplying it with the something?
An interesting exercise if nothing else.
A basic wrapper...
def wrapper(func,*args):
def wrapped():
return func(*args)
return wrapped
wrapper(print,"bob")
wrapper()
...which works. ie prints bob out
but I don't know how to make the below work - returning a FOR function made lots of syntax errors.
eg something like:
def for_1(y, do_something):
def wrapped():
return for x in y:
do_something
return wrapped
for_1(range(3),print("bob\n"))
for_1()
...and didn't see bob on the screen 3 times.
Could someone point me in the right direction, please? A wrapper is not doing the returned function.
Perhaps use a class for the wrapper? Then have my own methods(??)
...or maybe point me to someone's page who has done this before. I have explored wrappers and decorators but not seen something for passing parameters to a FOR loop function
You can simply restructure your code to not return too early and not call to early.
For this split up the function and parameters as two parameters to your for_1 wrapper.
If you want return value, gather them in your for loop and return them as a list.
def for_1(y, do_something, with_param):
for x in y:
do_something(with_param)
for_1(range(3), print, "bob")
Why make it complicated?
def for_1(y, to_print):
for x in range(y):
print(to_print)
for_1(3, "bob")
OUTPUT:
bob
bob
bob
EDIT:
def square(x):
print(x*x)
def for_1(y, command, param):
for x in range(y):
command(param)
for_1(1, square, 3)
OUTPUT:
9
the print is evaluated immediately and its return value passed in. what you want here is to pass in a callable, and append () to the do_something inside the loop. than you can use lambda for the passed in function.
def for_1(y, do_something):
def wrapped():
return for x in y:
do_something() # so we call whatever is passed in to be executed at this point
return wrapped
f = for_1(range(3),lambda: print("bob\n"))
f()
# or equivalent:
def print_bob():
print("bob\n")
for_1(range(3),print_bob)
below is my an example of what i am trying to do in my code...
def func():
x = int (input ('enter x: '))
return x
def func2():
y = int (input( 'enter y: '))
return y
def func3(x,y):
print(randomint(x,y))
def main():
func()
func2()
func3()
main()
What i am wondering is, why cant i use the x and y variables that i have defined via input and returned at the end of my functions? When this program tries to run it says the functions are missing required arguments. Silly i know, i am new to python.
furthermore, how can i use variable in one function i am creating, that were defined within another separate function? thanks!
You stated that you know how to indent so I'm not going to discuss that, the problem at hand is that you will need to catch the return value from func and func2 after they are caught.
You can do so like this:
def func():
x = int (input ('enter x: '))
return x
def func2():
y = int (input( 'enter y: '))
return y
def func3(x,y): # there's two positional value so you will need to pass two values to it when calling
print(randomint(x,y))
def main():
x = func() # catch the x
y = func2() # catch the y
func3(x,y) # pass along x and y which acts as the two positional values
# if you're lazy, you can directly do:
# func3(func(), func2()) which passes the return values directly to func3
main()
Another method is to use the global statement, but that isn't the best way for your case.
Just a hint: if you are using the random module, the random integer is called by: random.randint(x,y)
Your variables only live within the functions, there is no way for func3 to get x and y, but you have defined x and y as parameters. So far you're just not passing them in. The following should do.
def func():
x = int (input ('enter x: '))
return x
def func2():
y = int (input( 'enter y: '))
return y
def func3(x,y):
print(randomint(x,y))
def main():
x_val = func()
y_val = func2()
func3(x_val, y_val)
main()
Or just like this, if you don't want to use variables.
Just remember, same name doesn't mean it's the same variable. The scope can be different (method, function, elsewhere), and the name makes the variable unique ("the same") withhin the same scope. That is similar across all higher programming languages, but also, scopes can intersect, and in different ways. So that reuse example above, might, for example work in JavaScript.
This is probably closest to what you attempted to achieve:
def inX():
return int (input ('enter x: '))
def inY():
return int (input( 'enter y: '))
def PrintRand(x,y):
print(randomint(x,y))
def main():
PrintRand(InX(),InY()) # is probably closest to what you attempted to do.
main()
note that those slight renames do not have an effect other than understanding the code, but good names of methods telling what they actually do, are very important. You read the code many more times. You write it once.
Can someone explain why this code of python outputs 30? It seems like add = func ? But how does python knows this without declaring. It's a question in the python course from sololearn.com, a lot of people don't seem to understand
def add(x, y):
return x + y
def do_twice(func, x, y):
return func(func(x, y), func(x, y))
a = 5
b = 10
print(do_twice(add, a, b))
def do_twice(func, x, y):
return func(func(x, y), func(x, y))
when called with add, 5 and 10 will return
add(add(5, 10), add(5, 10))
i.e.
add(15, 15)
which is indeed 30
add has been passed as the first parameter, so is called func inside do_twice. Likewise a is 5 and b is 10.
A is set to 5 and B to 10. This add function simply returns the sum of two inputs.
You call do_twice with the add function, 5, and, 10 as inputs.
First, do_twice evaluates the sum of 5 and 10 in both inner calls of func(x, y). This leaves us with "return func(15, 15)". This adds 15 and 15, yielding 30. Finally, you print out this value. This is why it is 30. Feel free to follow up for any clarifications!
Python don't care what you pass in for func for your function do-twice.
But in the body of your function do_twice you are invoking func passed in i.e You are using func as if it supposed to be a callable(something you can invoke. A function is one such thing.). You can verify it by passing a string to do_twice and you should see an error stating string is not callable or something.
This question already has answers here:
Calling variable defined inside one function from another function
(6 answers)
Python: Variables aren't re-assigned
(2 answers)
Closed 7 years ago.
I tried the following and got an error message that "x is not defined".
def test():
x = 2
y = 3
return x
def main():
test()
print(2 + x)
main()
Why isn't it working?
x is defined in test, but not in main
This means that x is not defined in main's scope
Take a look at this question for more details regarding scope. Specifically this answer.
If you want to use the value assigned to x in test, you need to assign the return value of test to a name:
def main():
value_of_x_from_test = test() # This is the same as `x = 2` in `test`.
print(2 + value_of_x_from_test)
You need to assign x again, and the way to do that is say x = test(). The x from test only exists in x, which is why you need to reassign it.
It doesn't even have to be x, it could be y, or z: x is simply the name you return, the value you use in main() can be called anything!
Or, you can just call the function directly in main(), in which case you won't even need the first line in the main function:
def test():
x = 2
y = 3
return x
def main():
x = test()
print(2 + x) #or just `print(2 + test())`
main()
It's not working because of scope. X is defined in test, but not in main(). Try setting x = test() in main, and everything should work for you.
In order to get the value of x in main(), you have to assign it to something:
def main():
value = test() # The variable can be 'value' or any other valid name, including 'x'
print(2 + value)
Because of x is defined locally in test(), it cannot be used by main. Instead you can use directly the output of test as it is shown in the following code:
def main():
print(2 + test())
I have two files;
The first file, myProgram.py, is a python file with a number of functions
one of the functions contained inside is myFunction
this function would be called with
import myProgram
myProgram.thisFunction()
myProgram.thatFunction()
The second file contains a menu system, with calls to the functions in myProgram.py
I'd like to call a particular function based on an argument passed to a function in file2
def file2_function(function):
myProgram.function
file2_function(thisFunction(x,y,z))
which would essentially create myProgram.thisfunction(x,y,z) and execute it.
I guess I could do this using a bunch of if/elif statements, say:
def file2_function(function):
if function == 1:
myProgram.thisFunction
elif function == 2:
myProgram.thatFunction
Though that could get messy as I'm already using a lot of if/elif/else statements for the menu system.
Is there a better way (or is the if/elif route the way to go?)
The *args in the function file2_function means the arguments to be passed to the function in which it calls:
def func1(a):
print a
def file2_function(function,*args):
function(*args)
file2_function(func1,4)
#4
You can create a dictionary where key is the name of the function, and value is the function itself. Short example:
functions = { 'add' : lambda x,y : x + y, 'mult': lambda x,y : x * y, 'div' : lambda x,y : x / y, 'sub' : lambda x,y : x - y }
functions['add'](1,2) # returns 3
#aga gave you a good hint. When I'm writing cli applications I usually do smth like:
def func1():
pass
def func2():
pass
def func3():
pass
def func_caller(name):
func_dict = {
'func1': func1,
'func2': func2,
'func3': func3
}
try:
func_dict[name]()
except KeyError:
print "no such func"
Alternatively you have getattr. See following snippet:
>>> import sys
>>> getattr(sys,'exc_info')
<built-in function exc_info>
>>> getattr(sys,'exc_info')()
(None, None, None)