why this function return None to value? - python

total=0
def f(x):
import math
return 10*math.e**(math.log(0.5)/5.27 * x)
def radio(start,stop,step):
time=stop-start
newstart=start+step
if time !=0:
rad=f(start)*step
global total
total+=rad
radio(newstart,stop,step)
else:
return total
print radio(0, 5, 1)
print radio(5, 11, 1)
print radio(0, 11, 1)
print radio(40, 100, 1.5)

In Python functions return None by default.
You have problem with indentation, therefore your function radio unexpectedly ends and the subsequent code block considered an independent and not belonging to the radio. To solve it - fix the indentation like this:
def radio(start,stop,step):
time=stop-start
newstart=start+step
if time !=0:
rad=f(start)*step
global total
total+=rad
radio(newstart,stop,step)
else:
return total

In python function has to give any return value if no return value are specified then by default None is returned
The first time you called radio function nothing was returned it called itself again due to which None was returned
TO avoid this problem since you are using recursive call you have return value of each function to other function so use return when calling the same function
total=0
def f(x):
import math
return 10*math.e**(math.log(0.5)/5.27 * x)
def radio(start,stop,step):
time=stop-start
newstart=start+step
if time !=0:
rad=f(start)*step
global total
total+=rad
return radio(newstart,stop,step)
else:
return total
print radio(0, 5, 1)
Output:
39.1031878433

Related

How can I ensure that a function is "defined" in Python?

Trying to learn python as a java programmer. I would really appreciate some insight into why my program is telling me that my "isPrime" function isn't defined, especially with the use of 'self.'
import math
class Problem10:
def sumOfPrimesX(self, number):
sum = 0
for i in range(0, number):
if isPrime(i):
sum += i
return sum
def isPrime(self, x):
for n in range(0, math.floor(x/2)):
if x % n == 0:
return False
return True
print(sumOfPrimesX(input()))
all functions need it as their first parameter in a python program
No, only the instance methods, the methods related to a specific instance of a class. A simple function can need to parameter.
And you won't see the parameter self filled with the classic way of calling it, if you call the method on a instance it'll be filled by it
p = Problem10()
p.sumOfPrimesX(int(input("Give a value"))) # call on instance, one paramater given
# same as
Problem10.sumOfPrimesX(Problem10(), int(input("Give a value")))
# call on class itself, need to pass an instance as first to fill 'self
Also you need to wrap the input in an int, also start the loop at 2
p = Problem10()
print(p.sumOfPrimesX(int(input("Give a value"))))
class Problem10:
def isPrime(self, x):
for n in range(2, math.floor(x / 2)):
if x % n == 0:
return False
return True
The issue is both isPrime and sumofPrimesX are methods of the class Problem10.
Try the following:
import math
class Problem10:
def sumOfPrimesX(self, number):
sum = 0
for i in range(0, number):
if self.isPrime(i):
sum += i
return sum
def isPrime(self, x):
for n in range(0, math.floor(x/2)):
if x % n == 0:
return False
return True
pv = Problem10()
print(pv.sumOfPrimesX(input()))

How can I define a 'do_twice' function with using '*args'?

I've made a code to repete a function process:
def do_twice(func, *args):
func(func(args))
def div(number):
print(number[0]/2)
do_twice(div, 8)
The expected output is:
4.0
2.0
But the output is:
4.0
TypeError: 'NoneType' object is not subscriptable
At this point I thought: Seems like number is None in the second round.
And my guess prooved as correct:
…
def div(number):
print(number) # i know, actually i shouldn't call it div NOW...
# output:
4
None
What was my fault? Thanks in advance.
Te problem is that when 'div' is called for the first time it gets args as input and it is looking for args[0]. The seconds call to 'div' will return a number and args[0] will fail.
Code below seems to work:
def do_twice(func, *args):
return func(func(args))
def div(number):
return number[0] / 2 if isinstance(number, tuple) else number / 2
print(do_twice(div, 8))
It didn't take too many changes to fix.
def do_twice(func, *args):
func(func(args[0]))
def div(number):
result = number/2
print(result)
return result # Return the result
do_twice(div, 8)
div needs to return the result of its calculation in order for it to be stored by do_twice for the second iteration. Otherwise, your intuition is correct, you're dividing None on the second execution of div.
The key takeaway is:
Returning makes values accessible outside the function.
You are forgetting to return something from the functions:
def do_twice(func, *args, **kwargs):
return func(func(*args, **kwargs))
def div2(n):
x = n / 2
print(x) # For debugging. A function like this normally would not print.
return x
do_twice(div2, 8)
In the call func(func(args)), the function func does not return any value. Hence, func(args) doesn't provide the required number argument for func in the outer call
function div should be modified as follows
def div(number):
print(number[0]/2)
return [number[0]/2]

inside the function "bigger()", it has returned a value--a or b. so, why do still need "return"s before "bigger()"s in the function "median()"?

inside the function "bigger()", it has returned a value--a or b.
so, why do still need "return"s before "bigger()"s in the function "median()"?
Here is the code:
def bigger(a,b):
if a > b:
return a
else:
return b
def biggest(a,b,c):
return bigger(a,bigger(b,c))
def median(a,b,c):
if a == biggest(a,b,c):
return bigger(b,c) #the function "bigger()" above has returned a value,
#so, why still need a 'return' before bigger(b,c)?
elif b == biggest(a,b,c):
return bigger(a,c)
else:
return bigger(a,b)
I'll try to explain with examples, maybe it is simpler.
You have defined your bigger function, that returns a value, right?
def bigger(a,b):
if a > b:
return a
else:
return b
Now, you have defined a biggest function, and you are calling bigger from that function.
def biggest(a,b,c):
return bigger(a,bigger(b,c))
Now imagine the thousands of stuff that you could do with the value returned from bigger.
You could use the returned value from bigger anywhere within biggest function. For example:
def biggest(a,b,c):
some_var = bigger(a,bigger(b,c))
return some_var + 10
Or
def biggest(a,b,c):
list_of_values = []
list_of_values.append(bigger(a,bigger(b,c)))
But as you wish to use the value returned from bigger in the function that calls biggest , you should return that again so that the caller of biggest gets this value. Otherwise, it would get None which basically tells the caller "No value returned."
A function call is an expression. Consider the following:
def add(a, b):
a + b
x = add(3, 5)
Would you expect x to now have the value 8? You shouldn't because add did not return the value of the expression a+b. The correct definition would be
def add(a, b):
return a+b
Now consider this function:
def backwards_add(a, b):
add(b, a)
x = backwards_add(3, 5)
Again, would you expect that x has the value 8? Once again, you shouldn't because backwards_add did not return the value of the expression add(b, a). The correct definition is
def backwards_add(a, b):
return add(b, a)
There are some languages that implicitly return the value of the last expression executed in a function (cf. Perl
sub add {
$1 + $2;
}
my $x = add(3, 5); # x has the value 8
), but Python is not one of those languages. You must explicitly return a value, or it will return None for you.

Want to refer to variable in the outer function's scope from an inner function being returned

So I'm making a simple program that gets 2 functions(a and k) and one integer value(b), then it gets the formal parameter in the two functions(a and k) which is "x" and applies a condition x < b then based on the condition makes a function call, either a or b. But when I run the program it gives an error that x is not defined in the global frame. I want it to get "x" from the formal parameter assigned to the functions a and b and then get the condition based on that.
Here's my code
def square(x):
return x * x
def increment(x):
return x + 1
def piecewise(a, k, b):
if x<b:
return a
else:
return k
mak = piecewise(increment,square ,3 )
print(mak(1))
I guess you want to do something like this:
def piecewise(a, k, b):
def f(x):
if x < b:
return a(x)
else:
return k(x)
return f
However, I am not sure if it is a good practice. So, I leave my answer here to see the comments and learn if there is any problem with it.

Call function? Python

My problem is that I want:
and then I want it to get evaluted in the calc_energy function 360 times
and then store the result so I could count the year average, I want to calculate the energy average..
Should I call the function instead of return in def_decide(v)???
Could someone help me get in on the right track?
def calc_v(latitud):
for t in range(0,360):
v=(23.5*math.sin(math.pi*(t-80)/180)+90-latitud)/90
decide_v(v):
def decide_v(v):
if 0<v<1:
return(v**2)
if v>=1:
return(1)
if v<=0:
return(0)
def calc_energy(v):
W=self.area*random(0,1)*self.sundigit*v
return W
def sort(self,W):
W+=100/360
You can make a generator from calc_v and then use it as you would use a list of values (notice yield instead of return):
def calc_v(latitude):
for t in range(0,360):
v=(23.5*math.sin(math.pi*(t-80)/180)+90-latitude)/90
yield v
def decide_v(v):
if 0<v<1:
return v**2
elif v>=1:
return 1
else:
return 0
for v in calc_v(latitude):
print decide_v(v)
You can use recursion which is a function calling itself. Below you can see the function factorial is called within itself. http://www.python-course.eu/recursive_functions.php
def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res
I get the feeling that you don't really want to know how to loop a function. I think you just want to call your function in the example that you gave.
def calc_v(latitud):
for t in range(0,366):
v=(23.5*math.sin(math.pi*(t-80)/180)+90-latitud)/90
decide_v(v) # return v
def decide_v(v):
if 0<v<1:
print(v**2)
if v>=1:
print(1)
if v<=0:
print(0)
When you use the return statement in a function then you will leave the loop and the function, so your for loop will only run through t=0 then it will break out of the function. I think you just want to call your function and give it the variable v.

Categories