Why does my code not return anything

2020-05-10 11:44发布

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

标签: python return
5条回答
▲ chillily
2楼-- · 2020-05-10 12:22

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

查看更多
一夜七次
3楼-- · 2020-05-10 12:31

You have to explicitly use the return keyword. Probably where you currently have print c.

f needs to return ba after the while loop.

查看更多
Ridiculous、
4楼-- · 2020-05-10 12:35

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 writing

bisection()
查看更多
时光不老,我们不散
5楼-- · 2020-05-10 12:38

First you should add return ba to function f to make f return someting:

def f(x):
    m = 0
    ba = balance 
    while m < 12: 
        ba = (ba - x)*monthlyInterestRate 
        m += 1
    retrun ba

Then, add bisection() at the last of your script file to call it:

bisection()
查看更多
混吃等死
6楼-- · 2020-05-10 12:40

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 no return value because you have not made a Return statement. I would also refrain from using variables as Globals, it's typically bad practice. Instead, if you want to modify MonthlyInterestRate send it as a parameter to f() and return the new value.

bisection only returns if f(c) == 0 but f() does not have a Return 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 Returnstatement.

查看更多
登录 后发表回答