fairly new to programming and trying to learn Python at the moment. I have this code and I don't understand why I don't get a return value :(
balance = 3200
annualInterestRate = 0.2
monthlyInterestRate = (annualInterestRate/12 + 1)
def f(x):
m = 0
ba = balance
while m < 12:
ba = (ba - x)*monthlyInterestRate
m += 1
return ba
def bisection():
a = 0
b = balance
c = (a+b)/2
while a != b:
if f(c) == 0:
return c
elif f(c) < 0:
a = c
else:
b = c
c = (a+b)/2
return c
bisection()
Two reasons. One, your function f(x) does not have an explicit return statement. If a function doesn't contain an explicit return it will have an implicit one, that is "None" (None is a python object). Second, the only place where f(x) is called is in bisection() which itself is never being called. So, since none of your functions are ever called, your code isn't going to return anything. Try calling bisection() after defining it
You have to explicitly use the
return
keyword. Probably where you currently haveprint c
.f
needs to returnba
after the while loop.First of all, in your function
f
you don't have the return statement that you need if you want to check the equality with 0.After add the return statement in the
f
function you have to write the body of your program because you just have two functions but you don't call them to get a result value...I understand that your program has to use the
bisection function
writingFirst you should add
return ba
to functionf
to makef
return someting:Then, add
bisection()
at the last of your script file to call it:You're being unclear about what function you expect to return a value, but as I cannot comment and prod yet I'll provide a possible answer.
First of all, in this code you never actually call any of the functions. I'm assuming this is done elsewhere.
As for
f(x)
, there's noreturn value
because you have not made aReturn
statement. I would also refrain from using variables as Globals, it's typically bad practice. Instead, if you want to modifyMonthlyInterestRate
send it as a parameter tof()
and return the new value.bisection
only returns iff(c) == 0
butf()
does not have aReturn
statement, so that will never happen. Past that, once it exits the loop it will only print c so no return value there either.If you want to compare a function, it NEEDS a
Return
statement.