Change function definition based on condition





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







2















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.










share|improve this question




















  • 1





    Hint: try rewriting this program so that it uses only one def.

    – Kevin
    Jan 3 at 20:30






  • 1





    You need to call tax(i) inside the first loop over incomes, where you define the functions. Otherwise you're always calling whatever function was defined last in the previous loop. Sidenote: this is a pretty weird way of approaching the task, why not write one tax function with the ifs inside it?

    – jonrsharpe
    Jan 3 at 20:31













  • Thanks a lot for your helpful comment. I am aware that it is weird I actually did it in order to practice using function and the notion of conditionally defining functions

    – Oshri Weiss
    Jan 6 at 12:49


















2















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.










share|improve this question




















  • 1





    Hint: try rewriting this program so that it uses only one def.

    – Kevin
    Jan 3 at 20:30






  • 1





    You need to call tax(i) inside the first loop over incomes, where you define the functions. Otherwise you're always calling whatever function was defined last in the previous loop. Sidenote: this is a pretty weird way of approaching the task, why not write one tax function with the ifs inside it?

    – jonrsharpe
    Jan 3 at 20:31













  • Thanks a lot for your helpful comment. I am aware that it is weird I actually did it in order to practice using function and the notion of conditionally defining functions

    – Oshri Weiss
    Jan 6 at 12:49














2












2








2








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.










share|improve this question
















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.







python function for-loop if-statement






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 at 20:31









John Kugelman

248k54406460




248k54406460










asked Jan 3 at 20:27









Oshri WeissOshri Weiss

133




133








  • 1





    Hint: try rewriting this program so that it uses only one def.

    – Kevin
    Jan 3 at 20:30






  • 1





    You need to call tax(i) inside the first loop over incomes, where you define the functions. Otherwise you're always calling whatever function was defined last in the previous loop. Sidenote: this is a pretty weird way of approaching the task, why not write one tax function with the ifs inside it?

    – jonrsharpe
    Jan 3 at 20:31













  • Thanks a lot for your helpful comment. I am aware that it is weird I actually did it in order to practice using function and the notion of conditionally defining functions

    – Oshri Weiss
    Jan 6 at 12:49














  • 1





    Hint: try rewriting this program so that it uses only one def.

    – Kevin
    Jan 3 at 20:30






  • 1





    You need to call tax(i) inside the first loop over incomes, where you define the functions. Otherwise you're always calling whatever function was defined last in the previous loop. Sidenote: this is a pretty weird way of approaching the task, why not write one tax function with the ifs inside it?

    – jonrsharpe
    Jan 3 at 20:31













  • Thanks a lot for your helpful comment. I am aware that it is weird I actually did it in order to practice using function and the notion of conditionally defining functions

    – Oshri Weiss
    Jan 6 at 12:49








1




1





Hint: try rewriting this program so that it uses only one def.

– Kevin
Jan 3 at 20:30





Hint: try rewriting this program so that it uses only one def.

– Kevin
Jan 3 at 20:30




1




1





You need to call tax(i) inside the first loop over incomes, where you define the functions. Otherwise you're always calling whatever function was defined last in the previous loop. Sidenote: this is a pretty weird way of approaching the task, why not write one tax function with the ifs inside it?

– jonrsharpe
Jan 3 at 20:31







You need to call tax(i) inside the first loop over incomes, where you define the functions. Otherwise you're always calling whatever function was defined last in the previous loop. Sidenote: this is a pretty weird way of approaching the task, why not write one tax function with the ifs inside it?

– jonrsharpe
Jan 3 at 20:31















Thanks a lot for your helpful comment. I am aware that it is weird I actually did it in order to practice using function and the notion of conditionally defining functions

– Oshri Weiss
Jan 6 at 12:49





Thanks a lot for your helpful comment. I am aware that it is weird I actually did it in order to practice using function and the notion of conditionally defining functions

– Oshri Weiss
Jan 6 at 12:49












2 Answers
2






active

oldest

votes


















3














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)





share|improve this answer





















  • 1





    Thanks a lot for the comprehensive answer. I know that I did not have to use "redefined functions" but I used in order to test whether or not I understand the concept well enough. I wanted to understand why it did not work. I think that I got it now thanks.

    – Oshri Weiss
    Jan 3 at 23:59



















1














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.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54029341%2fchange-function-definition-based-on-condition%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    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)





    share|improve this answer





















    • 1





      Thanks a lot for the comprehensive answer. I know that I did not have to use "redefined functions" but I used in order to test whether or not I understand the concept well enough. I wanted to understand why it did not work. I think that I got it now thanks.

      – Oshri Weiss
      Jan 3 at 23:59
















    3














    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)





    share|improve this answer





















    • 1





      Thanks a lot for the comprehensive answer. I know that I did not have to use "redefined functions" but I used in order to test whether or not I understand the concept well enough. I wanted to understand why it did not work. I think that I got it now thanks.

      – Oshri Weiss
      Jan 3 at 23:59














    3












    3








    3







    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)





    share|improve this answer















    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)






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 3 at 20:36

























    answered Jan 3 at 20:31









    Patrick ArtnerPatrick Artner

    26.3k62544




    26.3k62544








    • 1





      Thanks a lot for the comprehensive answer. I know that I did not have to use "redefined functions" but I used in order to test whether or not I understand the concept well enough. I wanted to understand why it did not work. I think that I got it now thanks.

      – Oshri Weiss
      Jan 3 at 23:59














    • 1





      Thanks a lot for the comprehensive answer. I know that I did not have to use "redefined functions" but I used in order to test whether or not I understand the concept well enough. I wanted to understand why it did not work. I think that I got it now thanks.

      – Oshri Weiss
      Jan 3 at 23:59








    1




    1





    Thanks a lot for the comprehensive answer. I know that I did not have to use "redefined functions" but I used in order to test whether or not I understand the concept well enough. I wanted to understand why it did not work. I think that I got it now thanks.

    – Oshri Weiss
    Jan 3 at 23:59





    Thanks a lot for the comprehensive answer. I know that I did not have to use "redefined functions" but I used in order to test whether or not I understand the concept well enough. I wanted to understand why it did not work. I think that I got it now thanks.

    – Oshri Weiss
    Jan 3 at 23:59













    1














    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.






    share|improve this answer




























      1














      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.






      share|improve this answer


























        1












        1








        1







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 3 at 20:31









        JETMJETM

        2,15441731




        2,15441731






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54029341%2fchange-function-definition-based-on-condition%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas

            Can't read property showImagePicker of undefined in react native iOS