Python: Unable to return gift with nested function - python

def hypo(a,b):
def square(x): return x*x;
return math.sqrt(square(a) + square(b));
def secondfunction():
result = hypo(1,2);
print(result);
I am trying to learn Python myself but unable to understand what is wrong?
Expected Result something like this 2.23606797749979

I got it working using a lambda:
import math
def hypo(a,b):
square = lambda x: x * x
return math.sqrt(square(a) + square(b))
def secondfunction():
result = hypo(1, 2)
print(result)
secondfunction()
Output:
2.23606797749979
Also, you don't need semicolons in Python, unless you want to make a winky-face ;)

You need to call the function secondfunction() to get the result
def hypo(a,b):
return (a ** 2 + b ** 2) ** 0.5
def secondfunction():
print(hypo(1,2))
secondfunction()
Output:
2.23606797749979

You can try
def hypo(a,b):
def square(x):
return x*x
return math.sqrt(square(a) + square(b))
def secondfunction():
result = hypo(1,2)
print(result)
secondfunction()
or if you execute it from a script you can add at the end
if __name__ == '__main__':
secondfunction()
Output
2.23606797749979

Related

Late code evaluation and also printing the code

I want to pass code to a test() routine, which has to :
print the code
execute it
and finally do stuff with the result.
should handle args in the background
For quick code snippets I can use eval(code-string), like this:
def test_eval(expr_str, expected):
global a,b
res = eval(expr_str) == expected
print(f'{res} : {expr_str}')
but for:
code with assignment
test() should do argumentless calling of fun(), even for fun(a, b...)
or longer code
the approach is unusable.
SOLVED
def test(fun,expected,args):
res = fun(*args) == expected
expr = inspect.getsource(fun)
print(f'{res} : {expr}')
def tests():fun()
def w(a,b):#args
a += b #assignment
return a.sym == "(a + b)"
a = ...
b = ...
test(w,True,(a,b))
better ideas?

How to get return output from another script?

How can i get the output from another script?
My first script to run:
from test2 import *
class Test():
def todo (self):
mult()
addx()
if __name__ == '__main__':
Test().todo()
My second script named (test2.py):
def mult():
x= 2 * 4
print(x)
return x
def addx():
sum = x + 2
print("sum",sum)
Error:
NameError: name 'x' is not defined
In the function addx() you haven't declared x. I believe you want x from mult. So you can do something like this
def addx():
x = mult()
sum = x + 2
print("sum",sum)
You should use the return value of mult, to pass it to your second function addx as a parameter.
def todo (self):
x = mult()
addx(x)
I advise you to read the Python doc section about function : https://docs.python.org/fr/3/tutorial/controlflow.html#defining-functions
In test2.py, you have not defined x
def addx():
sum = x + 2
print("sum",sum)
The problem above is that the computer doesn't know what x is. You could pass it as a parameter:
def addx(x):
sum = x + 2
print("sum", sum)
and change your code to:
from test2 import *
class Test():
def todo(self):
addx(x=mult()) # whatever number you want
if __name__ == '__main__':
Test().todo()

Python switch case

I am trying to use dictionary as switch case on python, however, the parameter does not seem to be pass to the called function, please help:
def switchcase(num,cc):
def fa(num):
out= num*1.1;
def fb(num):
out= num*2.2;
def fc(num):
out= num*3.3;
def fd(num):
out= num*4.4;
options = {
"a":fa(num),
"b":fb(num),
"c":fc(num),
"d":fd(num)
}
out=0
options[cc];
return out
print switchcase(10,"a")
the output is 0, I could not figure out the problem
The problem is:
out=0
options[cc];
return out
Basically -- no matter what options[cc] gives you, you're going to return 0 because that's the value of out. Note that setting out in the various fa, fb, ... functions does not change the value of out in the caller.
You probably want:
def switchcase(num,cc):
def fa(num):
return num*1.1;
def fb(num):
return num*2.2;
def fc(num):
return num*3.3;
def fd(num):
return num*4.4;
options = {
"a":fa(num),
"b":fb(num),
"c":fc(num),
"d":fd(num)
}
return options[cc];
Also note that this will be horribly inefficient in practice. You're creating 4 functions (and calling each) every time you call switchcase.
I'm guessing that you actually want to create a pre-made map of functions. Then you can pick up the function that you actually want from the map and call it with the given number:
def fa(num):
return num*1.1
def fb(num):
return num*2.2
def fc(num):
return num*3.3
def fd(num):
return num*4.4
OPTIONS = {
"a":fa,
"b":fb,
"c":fc,
"d":fd
}
def switchcase(num,cc):
return OPTIONS[cc](num)
Here is an alternative take. You can just navigate to the necessary methods you have outside the switcher, and also pass optional arguments if you need:
def fa(num):
return num*1.1
def fb(num):
return num*2.2
def fc(num):
return num*3.3
def fd(num, option=1):
return num*4.4*option
def f_default(num):
return num
def switchcase(cc):
return {
"a":fa,
"b":fb,
"c":fc,
"d":fd,
}.get(cc, f_default)
print switchcase("a")(10) # for Python 3 --> print(switchcase("a")(10))
print switchcase("d")(10, 3) # for Python 3 --> print(switchcase("d")(10, 3))
print(switchcase("a")(10))
11.0
print(switchcase("d")(10, 3))
132.0
print(switchcase("ddd")(10))
10
Another shorter version would be:
def switchcase(num, cc):
return {
"a": lambda: num * 1.1,
"b": lambda: num * 2.2,
"c": lambda: num * 3.3,
"d": lambda: num * 4.4,
}.get(cc, lambda: None)()
print (switchcase(10,"a"))

Python decorator TypeError 'object is not callable'

I am trying to get myself familiar with decorators.
This is a program I created to do so, but it keeps giving me an TypeError: 'int' object is not callable error, which I don't know how to fix.
#Filename: decorator_practice.py
def add(x):
def add_1():
add_1 = x() + 1
return add_1
def minus(x):
def minus_1():
return x() - 1
return minus_1
def multi(x, times=2):
def multi_2():
return x() * 2
def multi_3():
return x() * 3
def multi_4():
return x() * 4
if times == 2:
return multi_2
elif times == 3:
return multi_3
elif times == 4:
return multi_4
else:
return "Please enter times between 2 and 4"
def create_x():
x = input('Give variable x a value: ')
return x
add(create_x()())
I run this and type: 5
Can anyone help me? Thanks!
Your create_x function returns an integer:
def create_x():
x = input('Give variable x a value: ')
return x
so create_x()() is never going to work.
Part of the problem is that you've used poor parameter names, which is confusing you - you have two xs which refer to two completely different things. Using your add decorator as an example, modify to:
def add(func):
def add_1():
return func() + 1 # you should return from the inner function
return add_1
Now hopefully it is clear that the argument to add should be a function, which is called inside add_1. Therefore you could do:
adder = add(create_x) # don't call create_x yet!
adder() # calling add_1, which calls create_x
which simplifies to:
add(create_x)() # note ordering of parentheses
Note that this could also be written:
#add
def create_x():
...
create_x()
where the syntax #add means create_x = add(create_x).
Once you've mastered simple decorators, note that your multi will not work as you expect - see e.g. python decorators with parameters for creating decorators that take arguments.
You have unnecessary (), change add(create_x()()) to add(create_x()),
and I suggest using x = int(raw_input('Give variable x a value: '))
See the following example:
def add(x):
def add_1():
#add_1 = x() + 1 # remove this line
return x+1
return add_1
def create_x():
x = input('Give variable x a value: ')
return x
b = add(create_x())
print 'answer: ', b()
localhost# python t.py
Give variable x a value: 5
answer: 6

Get inner function result without interaction of outer function in python

I want to get inner function result so i code it like
def main():
def sub():
a = 1
print a
exec main.__code__.co_consts[1]
using above code working successfully but i want to pass the argument to the sub function like...
def main():
def sub(x):
a = x + 1
return a
ans = exec main.__code__.co_consts[1]
print ans
in that problem is i don't know how to pass that x value.
that work must need to exec so that how to pass that x value with exec without interaction of main function
Maybe something like the code below, as suggested by this SO answer
def main():
def sub():
a = x + 1
print a
return a
exec(main.__code__.co_consts[1], {'x': 1} )

Categories