Oshri Weiss
Oshri Weiss

Reputation: 23

Change function definition based on condition

I am trying to define a conditional function that is the definition of the function depends on the input value. I also want it to run on several different inputs contained in a list.

The output that I am getting is not what I am expecting. For the following inputs: incomes = [500, 1500, 4000] I expect the output to be: 50, 200 but the actual outputs are: -150, 150 and 900 respectively. The outputs that I was expecting are: . I do get the correct output when I enter only one income value to the list.

incomes = [500, 1500, 4000]
for current_income in incomes:
    income = current_income
    if income <1000:
        def tax(income):
            return income*0.1
    elif 1000<=income<2000:
        def tax(income):
            return 1000*0.1 +(income-1000)*0.2
    else:
        def tax(income):
         return 1000*0.1+ 1000*0.2 + (income-2000)*0.3

for i in incomes:
    result = tax(i)
    print(result)

It seems that the order of values in the list matter : I reversed the order of incomes in the list I get the output of: 400, 150, 50. I understand that the problem lies in the interaction of the for loop and if, elsif and else conditions but I do not see what is actually wrong in my code.

Upvotes: 2

Views: 1655

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51683

Why are you conditionally create functions? Use one and decide inside it what tax is applied based on what income is inputted into it:

def tax(income):
    if income < 1000:
        return income*0.1
    elif 1000 <= income < 2000:
        return 1000*0.1 +(income-1000)*0.2             # 100 + ...
    else:
        return 1000*0.1 + 1000*0.2 + (income-2000)*0.3 # 300 + ...


incomes = [500, 1500, 4000]

for i in incomes:
    result = tax(i)
    print(result)

Output:

50.0
200.0
900.0

To use "redefined functions" as you try to you would need to put the print statement into the same loop to benefit from the currently defined tax function.

(VERY bad STYLE!)

incomes = [500, 1500, 4000]
for i in incomes: 
    if i <1000:
        def tax(income):
            return income*0.1
    elif 1000<=i<2000:
        def tax(income):
            return 1000*0.1 +(income-1000)*0.2
    else:
        def tax(income):
            return 1000*0.1+ 1000*0.2 + (income-2000)*0.3

    # use the tax function that _currently_ is valid for `tax`
    result = tax(i)
    print(result)

Upvotes: 3

user2201041
user2201041

Reputation:

The problem is that you keep redefining the tax function. When you finish your first for-loop, whatever you defined it as the last time is what you end up with.

The simplest workaround would be to put the check inside the function, as shown in the other answer.

If you need to conditionally create a function for some reason, you'll have to restructure things so that you use the function before you redefine it.

Upvotes: 1

Related Questions