calling different functions depending on variable values












-1















I have 500 floats in total and i want to run if statement on each of them and call a function accordingly



My code is something like this:



x1 = .2
x2 = .33
x3 = -.422
x4 = -1

def function1():
print("x1 is positive")

def function2():
print("x2 is positive")

def function3():
print("x3 is positive")

def function4():
print("x4 is positive")

for x in range(10):
if x1 > 0:
function1()

if x2 > 0:
function2()

if x3 > 0:
function3()

if x4 > 0:
function4()


I want a better more efficient way of doing this otherwise i have to write if statement for all the variables










share|improve this question


















  • 3





    Are each of those 500 float values stored in separate variables—i.e. x1, x2, ... x500? If they are, that's your first problem. If not, then please edit your question and show us what you're really dealing with.

    – martineau
    Jan 2 at 12:13













  • yes they are all separate variables

    – Gaurav
    Jan 2 at 15:35






  • 1





    In that case you need to put them all in some kind of container—a list seems suitable—and then you can easily handle them all with a single function. It looks like there's some kind if group-of-four, in which case you could use a list-of-lists-of-four-elements.

    – martineau
    Jan 2 at 16:58
















-1















I have 500 floats in total and i want to run if statement on each of them and call a function accordingly



My code is something like this:



x1 = .2
x2 = .33
x3 = -.422
x4 = -1

def function1():
print("x1 is positive")

def function2():
print("x2 is positive")

def function3():
print("x3 is positive")

def function4():
print("x4 is positive")

for x in range(10):
if x1 > 0:
function1()

if x2 > 0:
function2()

if x3 > 0:
function3()

if x4 > 0:
function4()


I want a better more efficient way of doing this otherwise i have to write if statement for all the variables










share|improve this question


















  • 3





    Are each of those 500 float values stored in separate variables—i.e. x1, x2, ... x500? If they are, that's your first problem. If not, then please edit your question and show us what you're really dealing with.

    – martineau
    Jan 2 at 12:13













  • yes they are all separate variables

    – Gaurav
    Jan 2 at 15:35






  • 1





    In that case you need to put them all in some kind of container—a list seems suitable—and then you can easily handle them all with a single function. It looks like there's some kind if group-of-four, in which case you could use a list-of-lists-of-four-elements.

    – martineau
    Jan 2 at 16:58














-1












-1








-1








I have 500 floats in total and i want to run if statement on each of them and call a function accordingly



My code is something like this:



x1 = .2
x2 = .33
x3 = -.422
x4 = -1

def function1():
print("x1 is positive")

def function2():
print("x2 is positive")

def function3():
print("x3 is positive")

def function4():
print("x4 is positive")

for x in range(10):
if x1 > 0:
function1()

if x2 > 0:
function2()

if x3 > 0:
function3()

if x4 > 0:
function4()


I want a better more efficient way of doing this otherwise i have to write if statement for all the variables










share|improve this question














I have 500 floats in total and i want to run if statement on each of them and call a function accordingly



My code is something like this:



x1 = .2
x2 = .33
x3 = -.422
x4 = -1

def function1():
print("x1 is positive")

def function2():
print("x2 is positive")

def function3():
print("x3 is positive")

def function4():
print("x4 is positive")

for x in range(10):
if x1 > 0:
function1()

if x2 > 0:
function2()

if x3 > 0:
function3()

if x4 > 0:
function4()


I want a better more efficient way of doing this otherwise i have to write if statement for all the variables







python python-3.x






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 2 at 11:23









GauravGaurav

62




62








  • 3





    Are each of those 500 float values stored in separate variables—i.e. x1, x2, ... x500? If they are, that's your first problem. If not, then please edit your question and show us what you're really dealing with.

    – martineau
    Jan 2 at 12:13













  • yes they are all separate variables

    – Gaurav
    Jan 2 at 15:35






  • 1





    In that case you need to put them all in some kind of container—a list seems suitable—and then you can easily handle them all with a single function. It looks like there's some kind if group-of-four, in which case you could use a list-of-lists-of-four-elements.

    – martineau
    Jan 2 at 16:58














  • 3





    Are each of those 500 float values stored in separate variables—i.e. x1, x2, ... x500? If they are, that's your first problem. If not, then please edit your question and show us what you're really dealing with.

    – martineau
    Jan 2 at 12:13













  • yes they are all separate variables

    – Gaurav
    Jan 2 at 15:35






  • 1





    In that case you need to put them all in some kind of container—a list seems suitable—and then you can easily handle them all with a single function. It looks like there's some kind if group-of-four, in which case you could use a list-of-lists-of-four-elements.

    – martineau
    Jan 2 at 16:58








3




3





Are each of those 500 float values stored in separate variables—i.e. x1, x2, ... x500? If they are, that's your first problem. If not, then please edit your question and show us what you're really dealing with.

– martineau
Jan 2 at 12:13







Are each of those 500 float values stored in separate variables—i.e. x1, x2, ... x500? If they are, that's your first problem. If not, then please edit your question and show us what you're really dealing with.

– martineau
Jan 2 at 12:13















yes they are all separate variables

– Gaurav
Jan 2 at 15:35





yes they are all separate variables

– Gaurav
Jan 2 at 15:35




1




1





In that case you need to put them all in some kind of container—a list seems suitable—and then you can easily handle them all with a single function. It looks like there's some kind if group-of-four, in which case you could use a list-of-lists-of-four-elements.

– martineau
Jan 2 at 16:58





In that case you need to put them all in some kind of container—a list seems suitable—and then you can easily handle them all with a single function. It looks like there's some kind if group-of-four, in which case you could use a list-of-lists-of-four-elements.

– martineau
Jan 2 at 16:58












2 Answers
2






active

oldest

votes


















1














You should take tutorial(s)to learn about python coding - this question is very basic as python goes.



Create a function that checks the variable and prints the correct thing:



x1 = .2
x2 = .33
x3 = -.422
x4 = -1

def check_and_print(value, variablename):
"""Checks if the content of value is smaller, bigger or euqal to zero.
Prints text to console using variablename."""
if value > 0:
print(f"{variablename} is positive")
elif value < 0:
print(f"{variablename} is negative")
else:
print(f"{variablename} is zero")

check_and_print(x1, "x1")
check_and_print(x2, "x2")
check_and_print(x3, "x3")
check_and_print(x4, "x4")
check_and_print(0, "carrot") # the given name is just printed


Output:



x1 is positive
x2 is positive
x3 is negative
x4 is negative
carrot is zero


You can shorten your code further by using a list of tuples and a loop over it:



for value,name in [(x1, "x1"),(x2, "x2"),(x3, "x3"),(x4, "x4"),(0, "x0")]:
check_and_print(value,name) # outputs the same as above


Doku:





  • functions

  • tuples

  • lists

  • loops

  • string formatting






share|improve this answer

































    0














    It would be much easier to do what you want if the data wasn't stored in a bunch of separately-named variables like x1, x2, ... x500, as you indicated in a comment.



    If you had the values in a list like this:



    values = [.2, .33, -.422, -1, .1, -.76, -.36, 1, -.6, .73, .22, .5,  # ... ,
    ]


    Then they could all be processed by a single function called repeatedly in a for loop as shown below:



    def check_value(index, value):
    if value > 0:
    print('x{} is positive'.format(index+1))

    for i, value in enumerate(values):
    check_value(i, value)


    You haven't indicated the source of the data, but I suspect it's being generated by an automated process of some sort. If you have control over how is done, then it shouldn't be too hard to change things so the values are in suggest form of a list.






    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%2f54005451%2fcalling-different-functions-depending-on-variable-values%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









      1














      You should take tutorial(s)to learn about python coding - this question is very basic as python goes.



      Create a function that checks the variable and prints the correct thing:



      x1 = .2
      x2 = .33
      x3 = -.422
      x4 = -1

      def check_and_print(value, variablename):
      """Checks if the content of value is smaller, bigger or euqal to zero.
      Prints text to console using variablename."""
      if value > 0:
      print(f"{variablename} is positive")
      elif value < 0:
      print(f"{variablename} is negative")
      else:
      print(f"{variablename} is zero")

      check_and_print(x1, "x1")
      check_and_print(x2, "x2")
      check_and_print(x3, "x3")
      check_and_print(x4, "x4")
      check_and_print(0, "carrot") # the given name is just printed


      Output:



      x1 is positive
      x2 is positive
      x3 is negative
      x4 is negative
      carrot is zero


      You can shorten your code further by using a list of tuples and a loop over it:



      for value,name in [(x1, "x1"),(x2, "x2"),(x3, "x3"),(x4, "x4"),(0, "x0")]:
      check_and_print(value,name) # outputs the same as above


      Doku:





      • functions

      • tuples

      • lists

      • loops

      • string formatting






      share|improve this answer






























        1














        You should take tutorial(s)to learn about python coding - this question is very basic as python goes.



        Create a function that checks the variable and prints the correct thing:



        x1 = .2
        x2 = .33
        x3 = -.422
        x4 = -1

        def check_and_print(value, variablename):
        """Checks if the content of value is smaller, bigger or euqal to zero.
        Prints text to console using variablename."""
        if value > 0:
        print(f"{variablename} is positive")
        elif value < 0:
        print(f"{variablename} is negative")
        else:
        print(f"{variablename} is zero")

        check_and_print(x1, "x1")
        check_and_print(x2, "x2")
        check_and_print(x3, "x3")
        check_and_print(x4, "x4")
        check_and_print(0, "carrot") # the given name is just printed


        Output:



        x1 is positive
        x2 is positive
        x3 is negative
        x4 is negative
        carrot is zero


        You can shorten your code further by using a list of tuples and a loop over it:



        for value,name in [(x1, "x1"),(x2, "x2"),(x3, "x3"),(x4, "x4"),(0, "x0")]:
        check_and_print(value,name) # outputs the same as above


        Doku:





        • functions

        • tuples

        • lists

        • loops

        • string formatting






        share|improve this answer




























          1












          1








          1







          You should take tutorial(s)to learn about python coding - this question is very basic as python goes.



          Create a function that checks the variable and prints the correct thing:



          x1 = .2
          x2 = .33
          x3 = -.422
          x4 = -1

          def check_and_print(value, variablename):
          """Checks if the content of value is smaller, bigger or euqal to zero.
          Prints text to console using variablename."""
          if value > 0:
          print(f"{variablename} is positive")
          elif value < 0:
          print(f"{variablename} is negative")
          else:
          print(f"{variablename} is zero")

          check_and_print(x1, "x1")
          check_and_print(x2, "x2")
          check_and_print(x3, "x3")
          check_and_print(x4, "x4")
          check_and_print(0, "carrot") # the given name is just printed


          Output:



          x1 is positive
          x2 is positive
          x3 is negative
          x4 is negative
          carrot is zero


          You can shorten your code further by using a list of tuples and a loop over it:



          for value,name in [(x1, "x1"),(x2, "x2"),(x3, "x3"),(x4, "x4"),(0, "x0")]:
          check_and_print(value,name) # outputs the same as above


          Doku:





          • functions

          • tuples

          • lists

          • loops

          • string formatting






          share|improve this answer















          You should take tutorial(s)to learn about python coding - this question is very basic as python goes.



          Create a function that checks the variable and prints the correct thing:



          x1 = .2
          x2 = .33
          x3 = -.422
          x4 = -1

          def check_and_print(value, variablename):
          """Checks if the content of value is smaller, bigger or euqal to zero.
          Prints text to console using variablename."""
          if value > 0:
          print(f"{variablename} is positive")
          elif value < 0:
          print(f"{variablename} is negative")
          else:
          print(f"{variablename} is zero")

          check_and_print(x1, "x1")
          check_and_print(x2, "x2")
          check_and_print(x3, "x3")
          check_and_print(x4, "x4")
          check_and_print(0, "carrot") # the given name is just printed


          Output:



          x1 is positive
          x2 is positive
          x3 is negative
          x4 is negative
          carrot is zero


          You can shorten your code further by using a list of tuples and a loop over it:



          for value,name in [(x1, "x1"),(x2, "x2"),(x3, "x3"),(x4, "x4"),(0, "x0")]:
          check_and_print(value,name) # outputs the same as above


          Doku:





          • functions

          • tuples

          • lists

          • loops

          • string formatting







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 2 at 11:47

























          answered Jan 2 at 11:37









          Patrick ArtnerPatrick Artner

          25.6k62544




          25.6k62544

























              0














              It would be much easier to do what you want if the data wasn't stored in a bunch of separately-named variables like x1, x2, ... x500, as you indicated in a comment.



              If you had the values in a list like this:



              values = [.2, .33, -.422, -1, .1, -.76, -.36, 1, -.6, .73, .22, .5,  # ... ,
              ]


              Then they could all be processed by a single function called repeatedly in a for loop as shown below:



              def check_value(index, value):
              if value > 0:
              print('x{} is positive'.format(index+1))

              for i, value in enumerate(values):
              check_value(i, value)


              You haven't indicated the source of the data, but I suspect it's being generated by an automated process of some sort. If you have control over how is done, then it shouldn't be too hard to change things so the values are in suggest form of a list.






              share|improve this answer






























                0














                It would be much easier to do what you want if the data wasn't stored in a bunch of separately-named variables like x1, x2, ... x500, as you indicated in a comment.



                If you had the values in a list like this:



                values = [.2, .33, -.422, -1, .1, -.76, -.36, 1, -.6, .73, .22, .5,  # ... ,
                ]


                Then they could all be processed by a single function called repeatedly in a for loop as shown below:



                def check_value(index, value):
                if value > 0:
                print('x{} is positive'.format(index+1))

                for i, value in enumerate(values):
                check_value(i, value)


                You haven't indicated the source of the data, but I suspect it's being generated by an automated process of some sort. If you have control over how is done, then it shouldn't be too hard to change things so the values are in suggest form of a list.






                share|improve this answer




























                  0












                  0








                  0







                  It would be much easier to do what you want if the data wasn't stored in a bunch of separately-named variables like x1, x2, ... x500, as you indicated in a comment.



                  If you had the values in a list like this:



                  values = [.2, .33, -.422, -1, .1, -.76, -.36, 1, -.6, .73, .22, .5,  # ... ,
                  ]


                  Then they could all be processed by a single function called repeatedly in a for loop as shown below:



                  def check_value(index, value):
                  if value > 0:
                  print('x{} is positive'.format(index+1))

                  for i, value in enumerate(values):
                  check_value(i, value)


                  You haven't indicated the source of the data, but I suspect it's being generated by an automated process of some sort. If you have control over how is done, then it shouldn't be too hard to change things so the values are in suggest form of a list.






                  share|improve this answer















                  It would be much easier to do what you want if the data wasn't stored in a bunch of separately-named variables like x1, x2, ... x500, as you indicated in a comment.



                  If you had the values in a list like this:



                  values = [.2, .33, -.422, -1, .1, -.76, -.36, 1, -.6, .73, .22, .5,  # ... ,
                  ]


                  Then they could all be processed by a single function called repeatedly in a for loop as shown below:



                  def check_value(index, value):
                  if value > 0:
                  print('x{} is positive'.format(index+1))

                  for i, value in enumerate(values):
                  check_value(i, value)


                  You haven't indicated the source of the data, but I suspect it's being generated by an automated process of some sort. If you have control over how is done, then it shouldn't be too hard to change things so the values are in suggest form of a list.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 2 at 21:57

























                  answered Jan 2 at 17:45









                  martineaumartineau

                  69.4k1092186




                  69.4k1092186






























                      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%2f54005451%2fcalling-different-functions-depending-on-variable-values%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

                      'app-layout' is not a known element: how to share Component with different Modules

                      android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                      SQL update select statement