简体   繁体   中英

Python returns nothing after recursive call

I am working on a python script that calculates an individual's tax based on their income.

The system of taxation requires that people are taxed based on how rich they are or how much they earn.

The first 1000 is not taxed,
The next 9000 is taxed 10% The next 10200 is taxed 15% The next 10550 is taxed 20% The next 19250 is taxed 25%
Anything left after the above is taxed at 30%

I have the code running and working and I am able to get the code working to follow the conditions above using recursion.

However, I have a problem returning the total_tax for the which should be the return value of the function.

For example, an income of 20500 should be taxed 2490.0 .

Here is my code snippet below:

def get_tax(income, current_level=0, total_tax=0,):
    level = [0, 0.1, 0.15, 0.2, 0.25, 0.3]
    amount = [1000, 9000, 10200, 10550, 19250, income]

    if income > 0 and current_level <=5:
        if income < amount[current_level]:
            this_tax = ( income * level[current_level] )
            income -= income

        else:    
            this_tax = ( level[current_level] * amount[current_level] )
            income -= amount[current_level]
            current_level += 1

        total_tax += this_tax
        print total_tax    
        get_tax(income, current_level, total_tax)

    else:
        final =  total_tax
        return final

get_tax(20500)

As you can see from the snippet, it does not work when I put the return statement in an else block, I have also tried doing it without the else block but it still does not work.

Here is a link to the snippet on Repl.it

It's returning nothing because you're not return ing.

return get_tax(income, current_level, total_tax) .

Now that it's returning something, you need to do something with the returned value.

The was not returning because the return statement was missing from the recursive call. Adding the return fixes it.

def get_tax(income, current_level=0, total_tax=0,):
    level = [0, 0.1, 0.15, 0.2, 0.25, 0.3]
    amount = [1000, 9000, 10200, 10550, 19250, income]
    
    if income > 0 and current_level <=5:
        if income < amount[current_level]:
            this_tax = ( income * level[current_level] )
            income -= income
            
        else:    
            this_tax = ( level[current_level] * amount[current_level] )
            income -= amount[current_level]
            current_level += 1
        
        total_tax += this_tax
        return get_tax(income, current_level, total_tax)
    
    else:
        final =  total_tax
        return final
print(get_tax(20500))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM