Back and forth loop Python

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
12
down vote

favorite
1












I want to create an infinite loop that counts up and down from 0 to 100 to 0 (and so on) and only stops when some convergence criterion inside the loop is met, so basically something like this:



for i in range(0, infinity):
for j in range(0, 100, 1):
print(j) # (in my case 100 lines of code)
for j in range(100, 0, -1):
print(j) # (same 100 lines of code as above)


Is there any way to merge the two for loops over j into one so that I don't have write out the same code inside the loops twice?







share|improve this question
















  • 3




    "so that I don't have write out the same code" Sounds like a good usecase for a function
    – DeepSpace
    Sep 5 at 14:16







  • 6




    @Phylogenesis TypeError: unsupported operand type(s) for +: 'range' and 'range'. This will only work in Python 2
    – DeepSpace
    Sep 5 at 14:18











  • Yeah, that's Python 2 only.
    – Phylogenesis
    Sep 5 at 14:19







  • 3




    Three sidenotes: range(100, 0, -1) does not actually produce range(0, 100, 1) in reverse. If you meant to go from 0 through to 99 included, then from 99 back to 0, use range(99, -1, -1). range(100) is the shorter form for range(0, 100, 1), it is good practice to use that instead. And there is no range(0, infinity) syntax, you'd use for i in itertools.count(): perhaps to create an infinite counter, or while True: to create an endless loop.
    – Martijn Pieters♦
    Sep 5 at 14:27














up vote
12
down vote

favorite
1












I want to create an infinite loop that counts up and down from 0 to 100 to 0 (and so on) and only stops when some convergence criterion inside the loop is met, so basically something like this:



for i in range(0, infinity):
for j in range(0, 100, 1):
print(j) # (in my case 100 lines of code)
for j in range(100, 0, -1):
print(j) # (same 100 lines of code as above)


Is there any way to merge the two for loops over j into one so that I don't have write out the same code inside the loops twice?







share|improve this question
















  • 3




    "so that I don't have write out the same code" Sounds like a good usecase for a function
    – DeepSpace
    Sep 5 at 14:16







  • 6




    @Phylogenesis TypeError: unsupported operand type(s) for +: 'range' and 'range'. This will only work in Python 2
    – DeepSpace
    Sep 5 at 14:18











  • Yeah, that's Python 2 only.
    – Phylogenesis
    Sep 5 at 14:19







  • 3




    Three sidenotes: range(100, 0, -1) does not actually produce range(0, 100, 1) in reverse. If you meant to go from 0 through to 99 included, then from 99 back to 0, use range(99, -1, -1). range(100) is the shorter form for range(0, 100, 1), it is good practice to use that instead. And there is no range(0, infinity) syntax, you'd use for i in itertools.count(): perhaps to create an infinite counter, or while True: to create an endless loop.
    – Martijn Pieters♦
    Sep 5 at 14:27












up vote
12
down vote

favorite
1









up vote
12
down vote

favorite
1






1





I want to create an infinite loop that counts up and down from 0 to 100 to 0 (and so on) and only stops when some convergence criterion inside the loop is met, so basically something like this:



for i in range(0, infinity):
for j in range(0, 100, 1):
print(j) # (in my case 100 lines of code)
for j in range(100, 0, -1):
print(j) # (same 100 lines of code as above)


Is there any way to merge the two for loops over j into one so that I don't have write out the same code inside the loops twice?







share|improve this question












I want to create an infinite loop that counts up and down from 0 to 100 to 0 (and so on) and only stops when some convergence criterion inside the loop is met, so basically something like this:



for i in range(0, infinity):
for j in range(0, 100, 1):
print(j) # (in my case 100 lines of code)
for j in range(100, 0, -1):
print(j) # (same 100 lines of code as above)


Is there any way to merge the two for loops over j into one so that I don't have write out the same code inside the loops twice?









share|improve this question











share|improve this question




share|improve this question










asked Sep 5 at 14:13









Daniel

708




708







  • 3




    "so that I don't have write out the same code" Sounds like a good usecase for a function
    – DeepSpace
    Sep 5 at 14:16







  • 6




    @Phylogenesis TypeError: unsupported operand type(s) for +: 'range' and 'range'. This will only work in Python 2
    – DeepSpace
    Sep 5 at 14:18











  • Yeah, that's Python 2 only.
    – Phylogenesis
    Sep 5 at 14:19







  • 3




    Three sidenotes: range(100, 0, -1) does not actually produce range(0, 100, 1) in reverse. If you meant to go from 0 through to 99 included, then from 99 back to 0, use range(99, -1, -1). range(100) is the shorter form for range(0, 100, 1), it is good practice to use that instead. And there is no range(0, infinity) syntax, you'd use for i in itertools.count(): perhaps to create an infinite counter, or while True: to create an endless loop.
    – Martijn Pieters♦
    Sep 5 at 14:27












  • 3




    "so that I don't have write out the same code" Sounds like a good usecase for a function
    – DeepSpace
    Sep 5 at 14:16







  • 6




    @Phylogenesis TypeError: unsupported operand type(s) for +: 'range' and 'range'. This will only work in Python 2
    – DeepSpace
    Sep 5 at 14:18











  • Yeah, that's Python 2 only.
    – Phylogenesis
    Sep 5 at 14:19







  • 3




    Three sidenotes: range(100, 0, -1) does not actually produce range(0, 100, 1) in reverse. If you meant to go from 0 through to 99 included, then from 99 back to 0, use range(99, -1, -1). range(100) is the shorter form for range(0, 100, 1), it is good practice to use that instead. And there is no range(0, infinity) syntax, you'd use for i in itertools.count(): perhaps to create an infinite counter, or while True: to create an endless loop.
    – Martijn Pieters♦
    Sep 5 at 14:27







3




3




"so that I don't have write out the same code" Sounds like a good usecase for a function
– DeepSpace
Sep 5 at 14:16





"so that I don't have write out the same code" Sounds like a good usecase for a function
– DeepSpace
Sep 5 at 14:16





6




6




@Phylogenesis TypeError: unsupported operand type(s) for +: 'range' and 'range'. This will only work in Python 2
– DeepSpace
Sep 5 at 14:18





@Phylogenesis TypeError: unsupported operand type(s) for +: 'range' and 'range'. This will only work in Python 2
– DeepSpace
Sep 5 at 14:18













Yeah, that's Python 2 only.
– Phylogenesis
Sep 5 at 14:19





Yeah, that's Python 2 only.
– Phylogenesis
Sep 5 at 14:19





3




3




Three sidenotes: range(100, 0, -1) does not actually produce range(0, 100, 1) in reverse. If you meant to go from 0 through to 99 included, then from 99 back to 0, use range(99, -1, -1). range(100) is the shorter form for range(0, 100, 1), it is good practice to use that instead. And there is no range(0, infinity) syntax, you'd use for i in itertools.count(): perhaps to create an infinite counter, or while True: to create an endless loop.
– Martijn Pieters♦
Sep 5 at 14:27




Three sidenotes: range(100, 0, -1) does not actually produce range(0, 100, 1) in reverse. If you meant to go from 0 through to 99 included, then from 99 back to 0, use range(99, -1, -1). range(100) is the shorter form for range(0, 100, 1), it is good practice to use that instead. And there is no range(0, infinity) syntax, you'd use for i in itertools.count(): perhaps to create an infinite counter, or while True: to create an endless loop.
– Martijn Pieters♦
Sep 5 at 14:27












9 Answers
9






active

oldest

votes

















up vote
34
down vote



accepted










Use the chain method of itertools



import itertools
for i in range(0, infinity):
for j in itertools.chain(range(0, 100, 1), range(100, 0, -1)):
print(j) # (in my case 100 lines of code)


As suggested by @Chepner, you can use itertools.cycle() for the infinite loop:



from itertools import cycle, chain

for i in cycle(chain(range(0, 100, 1), range(100, 0, -1))):
....





share|improve this answer


















  • 12




    You can add itertools.cycle to this as well, to avoid the nested loop. for i in cycle(chain(range(100), range(100,0,-1)).
    – chepner
    Sep 5 at 14:23










  • As commented by @MartijnPieters it uses too much memory at once
    – N Chauhan
    Sep 5 at 14:23






  • 1




    @damienfrancois: I disagree that generic unpacking is better. Try that technique with range(10**6), range(10**6, -1, -1), and watch the memory footprint.
    – Martijn Pieters♦
    Sep 5 at 14:24











  • @MartijnPieters Noted. Thanks for the feedback
    – damienfrancois
    Sep 5 at 14:24

















up vote
14
down vote













As well as the other answers you can use a bit of maths:



while(True):
for i in range(200):
if i > 100:
i = 200 - i





share|improve this answer





























    up vote
    7
    down vote













    Here's yet another possibility:



    while notConverged:
    for i in xrange(-100, 101):
    print 100 - abs(i)





    share|improve this answer




















    • A very interesting approach! +1
      – N Chauhan
      Sep 5 at 20:32

















    up vote
    4
    down vote













    If you've got a repeated set of code, use a function to save space and effort:



    def function(x, y, x, num_from_for_loop):
    # 100 lines of code

    while not condition:
    for i in range(1, 101):
    if condition:
    break
    function(x, y, z, i)
    for i in range(100, 0, -1):
    if condition:
    break
    function(x, y, z, i)


    You could even use a while True






    share|improve this answer




















    • +1... I think a lot of the "ooo, I know just the itertools function to help!" answers are neglecting the big picture.
      – Sneftel
      Sep 5 at 20:28










    • I agree, although I honestly don't know anything about itertools save for a few of the simple functions.
      – N Chauhan
      Sep 5 at 20:31

















    up vote
    3
    down vote













    If you're using Python 3.5+, you can using generic unpacking:



    for j in (*range(0, 100, 1), *range(100, 0, -1)):


    or prior to Python 3.5, you can use itertools.chain:



    from itertools import chain

    ...

    for j in chain(range(0, 100, 1), range(100, 0, -1)):





    share|improve this answer
















    • 14




      Generic unpacking creates a huge tuple with all integers materialised (remember that range() is a very lightweight object). Chaining is better!
      – Martijn Pieters♦
      Sep 5 at 14:22


















    up vote
    3
    down vote













    up = True # since we want to go from 0 to 100 first

    while True: #for infinite loop

    # For up == True we will print 0-->100 (0,100,1)
    # For up == False we will print 100-->0 (100,0,-1)


    start,stop,step = (0,100,1) if up else (100,0,-1)
    for i in range(start,stop,step):
    print(i)

    up = not up # if we have just printed from 0-->100 (ie up==True), we want to print 100-->0 next so make up False ie up = not up( True)

    # up will help toggle, between 0-->100 and 100-->0





    share|improve this answer


















    • 1




      Pro tip for inverting a boolean: up ^= True
      – wjandrea
      Sep 6 at 0:58










    • @wjandrea Yes thanks for commenting forgot to add as a side note, I was going to use it but then I thought to keep it simple in case OP was beginner.
      – Tanmay jain
      Sep 6 at 3:22

















    up vote
    1
    down vote













    def up_down(lowest_value, highest_value):
    current = lowest_value
    delta = 1
    while True: # Begin infinite loop
    yield current
    current += delta
    if current <= lowest_value or current >= highest_value:
    delta *= -1 # Turn around when either limit is hit


    This defines a generator, which will continue to yield values for as long as you need. For example:



    >>> u = up_down(0, 10)
    >>> count = 0
    >>> for j in u:
    print(j) # for demonstration purposes
    count += 1 # your other 100 lines of code here
    if count >= 25: # your ending condition here
    break


    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    9
    8
    7
    6
    5
    4
    3
    2
    1
    0
    1
    2
    3
    4





    share|improve this answer



























      up vote
      0
      down vote













      This is more of a partial answer than a direct answer to your question, but you can also use the notion of trigonometric functions and their oscillation to imitate a 'back and forth' loop.



      If we have a cos function with an amplitude of 100, shifted left and upwards so that f(x) = 0 and 0 <= f(x) <= 100, we then have the formula f(x) = 50(cos(x-pi)+1) (plot of graph may be found here. The range is what you require, and oscillation occurs so there's no need to negate any values.



      >>> from math import cos, pi
      >>> f = lambda x: 50*(cos(x-pi)+1)
      >>> f(0)
      0.0
      >>> f(pi/2)
      50.0
      >>> f(pi)
      100.0
      >>> f(3*pi/2)
      50.0
      >>> f(2*pi)
      0.0


      The issue of course comes in that the function doesn't give integer values so easily, thus it's not that helpful - but this may be useful for future readers where trigonometric functions might be helpful for their case.






      share|improve this answer



























        up vote
        0
        down vote













        I had a similar problem a while ago where I also wanted to create values in the form of an infinite triangle wave, but wanted to step over some values. I ended up using a generator (and the range function as other also have been using):



        def tri_wave(min, max, step=1):
        while True:
        yield from range(min, max, step)
        yield from range(max, min, -1 * step)


        With carefully selected values on min, max and step (i.e. evenly divisible),



        for value in tri_wave(0, 8, 2):
        print(value, end=", ")


        I get the min and max value only once, which was my goal:



        ...0, 2, 4, 6, 8, 6, 4, 2, 0, 2, 4, 6, 8, 6, 4...


        I was using Python 3.6 at the time.






        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',
          convertImagesToLinks: true,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          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%2f52187275%2fback-and-forth-loop-python%23new-answer', 'question_page');

          );

          Post as a guest






























          9 Answers
          9






          active

          oldest

          votes








          9 Answers
          9






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          34
          down vote



          accepted










          Use the chain method of itertools



          import itertools
          for i in range(0, infinity):
          for j in itertools.chain(range(0, 100, 1), range(100, 0, -1)):
          print(j) # (in my case 100 lines of code)


          As suggested by @Chepner, you can use itertools.cycle() for the infinite loop:



          from itertools import cycle, chain

          for i in cycle(chain(range(0, 100, 1), range(100, 0, -1))):
          ....





          share|improve this answer


















          • 12




            You can add itertools.cycle to this as well, to avoid the nested loop. for i in cycle(chain(range(100), range(100,0,-1)).
            – chepner
            Sep 5 at 14:23










          • As commented by @MartijnPieters it uses too much memory at once
            – N Chauhan
            Sep 5 at 14:23






          • 1




            @damienfrancois: I disagree that generic unpacking is better. Try that technique with range(10**6), range(10**6, -1, -1), and watch the memory footprint.
            – Martijn Pieters♦
            Sep 5 at 14:24











          • @MartijnPieters Noted. Thanks for the feedback
            – damienfrancois
            Sep 5 at 14:24














          up vote
          34
          down vote



          accepted










          Use the chain method of itertools



          import itertools
          for i in range(0, infinity):
          for j in itertools.chain(range(0, 100, 1), range(100, 0, -1)):
          print(j) # (in my case 100 lines of code)


          As suggested by @Chepner, you can use itertools.cycle() for the infinite loop:



          from itertools import cycle, chain

          for i in cycle(chain(range(0, 100, 1), range(100, 0, -1))):
          ....





          share|improve this answer


















          • 12




            You can add itertools.cycle to this as well, to avoid the nested loop. for i in cycle(chain(range(100), range(100,0,-1)).
            – chepner
            Sep 5 at 14:23










          • As commented by @MartijnPieters it uses too much memory at once
            – N Chauhan
            Sep 5 at 14:23






          • 1




            @damienfrancois: I disagree that generic unpacking is better. Try that technique with range(10**6), range(10**6, -1, -1), and watch the memory footprint.
            – Martijn Pieters♦
            Sep 5 at 14:24











          • @MartijnPieters Noted. Thanks for the feedback
            – damienfrancois
            Sep 5 at 14:24












          up vote
          34
          down vote



          accepted







          up vote
          34
          down vote



          accepted






          Use the chain method of itertools



          import itertools
          for i in range(0, infinity):
          for j in itertools.chain(range(0, 100, 1), range(100, 0, -1)):
          print(j) # (in my case 100 lines of code)


          As suggested by @Chepner, you can use itertools.cycle() for the infinite loop:



          from itertools import cycle, chain

          for i in cycle(chain(range(0, 100, 1), range(100, 0, -1))):
          ....





          share|improve this answer














          Use the chain method of itertools



          import itertools
          for i in range(0, infinity):
          for j in itertools.chain(range(0, 100, 1), range(100, 0, -1)):
          print(j) # (in my case 100 lines of code)


          As suggested by @Chepner, you can use itertools.cycle() for the infinite loop:



          from itertools import cycle, chain

          for i in cycle(chain(range(0, 100, 1), range(100, 0, -1))):
          ....






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Sep 6 at 6:01

























          answered Sep 5 at 14:19









          damienfrancois

          23.4k43959




          23.4k43959







          • 12




            You can add itertools.cycle to this as well, to avoid the nested loop. for i in cycle(chain(range(100), range(100,0,-1)).
            – chepner
            Sep 5 at 14:23










          • As commented by @MartijnPieters it uses too much memory at once
            – N Chauhan
            Sep 5 at 14:23






          • 1




            @damienfrancois: I disagree that generic unpacking is better. Try that technique with range(10**6), range(10**6, -1, -1), and watch the memory footprint.
            – Martijn Pieters♦
            Sep 5 at 14:24











          • @MartijnPieters Noted. Thanks for the feedback
            – damienfrancois
            Sep 5 at 14:24












          • 12




            You can add itertools.cycle to this as well, to avoid the nested loop. for i in cycle(chain(range(100), range(100,0,-1)).
            – chepner
            Sep 5 at 14:23










          • As commented by @MartijnPieters it uses too much memory at once
            – N Chauhan
            Sep 5 at 14:23






          • 1




            @damienfrancois: I disagree that generic unpacking is better. Try that technique with range(10**6), range(10**6, -1, -1), and watch the memory footprint.
            – Martijn Pieters♦
            Sep 5 at 14:24











          • @MartijnPieters Noted. Thanks for the feedback
            – damienfrancois
            Sep 5 at 14:24







          12




          12




          You can add itertools.cycle to this as well, to avoid the nested loop. for i in cycle(chain(range(100), range(100,0,-1)).
          – chepner
          Sep 5 at 14:23




          You can add itertools.cycle to this as well, to avoid the nested loop. for i in cycle(chain(range(100), range(100,0,-1)).
          – chepner
          Sep 5 at 14:23












          As commented by @MartijnPieters it uses too much memory at once
          – N Chauhan
          Sep 5 at 14:23




          As commented by @MartijnPieters it uses too much memory at once
          – N Chauhan
          Sep 5 at 14:23




          1




          1




          @damienfrancois: I disagree that generic unpacking is better. Try that technique with range(10**6), range(10**6, -1, -1), and watch the memory footprint.
          – Martijn Pieters♦
          Sep 5 at 14:24





          @damienfrancois: I disagree that generic unpacking is better. Try that technique with range(10**6), range(10**6, -1, -1), and watch the memory footprint.
          – Martijn Pieters♦
          Sep 5 at 14:24













          @MartijnPieters Noted. Thanks for the feedback
          – damienfrancois
          Sep 5 at 14:24




          @MartijnPieters Noted. Thanks for the feedback
          – damienfrancois
          Sep 5 at 14:24












          up vote
          14
          down vote













          As well as the other answers you can use a bit of maths:



          while(True):
          for i in range(200):
          if i > 100:
          i = 200 - i





          share|improve this answer


























            up vote
            14
            down vote













            As well as the other answers you can use a bit of maths:



            while(True):
            for i in range(200):
            if i > 100:
            i = 200 - i





            share|improve this answer
























              up vote
              14
              down vote










              up vote
              14
              down vote









              As well as the other answers you can use a bit of maths:



              while(True):
              for i in range(200):
              if i > 100:
              i = 200 - i





              share|improve this answer














              As well as the other answers you can use a bit of maths:



              while(True):
              for i in range(200):
              if i > 100:
              i = 200 - i






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Sep 5 at 14:24

























              answered Sep 5 at 14:21









              ncfirth

              3,206730




              3,206730




















                  up vote
                  7
                  down vote













                  Here's yet another possibility:



                  while notConverged:
                  for i in xrange(-100, 101):
                  print 100 - abs(i)





                  share|improve this answer




















                  • A very interesting approach! +1
                    – N Chauhan
                    Sep 5 at 20:32














                  up vote
                  7
                  down vote













                  Here's yet another possibility:



                  while notConverged:
                  for i in xrange(-100, 101):
                  print 100 - abs(i)





                  share|improve this answer




















                  • A very interesting approach! +1
                    – N Chauhan
                    Sep 5 at 20:32












                  up vote
                  7
                  down vote










                  up vote
                  7
                  down vote









                  Here's yet another possibility:



                  while notConverged:
                  for i in xrange(-100, 101):
                  print 100 - abs(i)





                  share|improve this answer












                  Here's yet another possibility:



                  while notConverged:
                  for i in xrange(-100, 101):
                  print 100 - abs(i)






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 5 at 19:52









                  twalberg

                  40.2k76364




                  40.2k76364











                  • A very interesting approach! +1
                    – N Chauhan
                    Sep 5 at 20:32
















                  • A very interesting approach! +1
                    – N Chauhan
                    Sep 5 at 20:32















                  A very interesting approach! +1
                  – N Chauhan
                  Sep 5 at 20:32




                  A very interesting approach! +1
                  – N Chauhan
                  Sep 5 at 20:32










                  up vote
                  4
                  down vote













                  If you've got a repeated set of code, use a function to save space and effort:



                  def function(x, y, x, num_from_for_loop):
                  # 100 lines of code

                  while not condition:
                  for i in range(1, 101):
                  if condition:
                  break
                  function(x, y, z, i)
                  for i in range(100, 0, -1):
                  if condition:
                  break
                  function(x, y, z, i)


                  You could even use a while True






                  share|improve this answer




















                  • +1... I think a lot of the "ooo, I know just the itertools function to help!" answers are neglecting the big picture.
                    – Sneftel
                    Sep 5 at 20:28










                  • I agree, although I honestly don't know anything about itertools save for a few of the simple functions.
                    – N Chauhan
                    Sep 5 at 20:31














                  up vote
                  4
                  down vote













                  If you've got a repeated set of code, use a function to save space and effort:



                  def function(x, y, x, num_from_for_loop):
                  # 100 lines of code

                  while not condition:
                  for i in range(1, 101):
                  if condition:
                  break
                  function(x, y, z, i)
                  for i in range(100, 0, -1):
                  if condition:
                  break
                  function(x, y, z, i)


                  You could even use a while True






                  share|improve this answer




















                  • +1... I think a lot of the "ooo, I know just the itertools function to help!" answers are neglecting the big picture.
                    – Sneftel
                    Sep 5 at 20:28










                  • I agree, although I honestly don't know anything about itertools save for a few of the simple functions.
                    – N Chauhan
                    Sep 5 at 20:31












                  up vote
                  4
                  down vote










                  up vote
                  4
                  down vote









                  If you've got a repeated set of code, use a function to save space and effort:



                  def function(x, y, x, num_from_for_loop):
                  # 100 lines of code

                  while not condition:
                  for i in range(1, 101):
                  if condition:
                  break
                  function(x, y, z, i)
                  for i in range(100, 0, -1):
                  if condition:
                  break
                  function(x, y, z, i)


                  You could even use a while True






                  share|improve this answer












                  If you've got a repeated set of code, use a function to save space and effort:



                  def function(x, y, x, num_from_for_loop):
                  # 100 lines of code

                  while not condition:
                  for i in range(1, 101):
                  if condition:
                  break
                  function(x, y, z, i)
                  for i in range(100, 0, -1):
                  if condition:
                  break
                  function(x, y, z, i)


                  You could even use a while True







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 5 at 14:22









                  N Chauhan

                  945111




                  945111











                  • +1... I think a lot of the "ooo, I know just the itertools function to help!" answers are neglecting the big picture.
                    – Sneftel
                    Sep 5 at 20:28










                  • I agree, although I honestly don't know anything about itertools save for a few of the simple functions.
                    – N Chauhan
                    Sep 5 at 20:31
















                  • +1... I think a lot of the "ooo, I know just the itertools function to help!" answers are neglecting the big picture.
                    – Sneftel
                    Sep 5 at 20:28










                  • I agree, although I honestly don't know anything about itertools save for a few of the simple functions.
                    – N Chauhan
                    Sep 5 at 20:31















                  +1... I think a lot of the "ooo, I know just the itertools function to help!" answers are neglecting the big picture.
                  – Sneftel
                  Sep 5 at 20:28




                  +1... I think a lot of the "ooo, I know just the itertools function to help!" answers are neglecting the big picture.
                  – Sneftel
                  Sep 5 at 20:28












                  I agree, although I honestly don't know anything about itertools save for a few of the simple functions.
                  – N Chauhan
                  Sep 5 at 20:31




                  I agree, although I honestly don't know anything about itertools save for a few of the simple functions.
                  – N Chauhan
                  Sep 5 at 20:31










                  up vote
                  3
                  down vote













                  If you're using Python 3.5+, you can using generic unpacking:



                  for j in (*range(0, 100, 1), *range(100, 0, -1)):


                  or prior to Python 3.5, you can use itertools.chain:



                  from itertools import chain

                  ...

                  for j in chain(range(0, 100, 1), range(100, 0, -1)):





                  share|improve this answer
















                  • 14




                    Generic unpacking creates a huge tuple with all integers materialised (remember that range() is a very lightweight object). Chaining is better!
                    – Martijn Pieters♦
                    Sep 5 at 14:22















                  up vote
                  3
                  down vote













                  If you're using Python 3.5+, you can using generic unpacking:



                  for j in (*range(0, 100, 1), *range(100, 0, -1)):


                  or prior to Python 3.5, you can use itertools.chain:



                  from itertools import chain

                  ...

                  for j in chain(range(0, 100, 1), range(100, 0, -1)):





                  share|improve this answer
















                  • 14




                    Generic unpacking creates a huge tuple with all integers materialised (remember that range() is a very lightweight object). Chaining is better!
                    – Martijn Pieters♦
                    Sep 5 at 14:22













                  up vote
                  3
                  down vote










                  up vote
                  3
                  down vote









                  If you're using Python 3.5+, you can using generic unpacking:



                  for j in (*range(0, 100, 1), *range(100, 0, -1)):


                  or prior to Python 3.5, you can use itertools.chain:



                  from itertools import chain

                  ...

                  for j in chain(range(0, 100, 1), range(100, 0, -1)):





                  share|improve this answer












                  If you're using Python 3.5+, you can using generic unpacking:



                  for j in (*range(0, 100, 1), *range(100, 0, -1)):


                  or prior to Python 3.5, you can use itertools.chain:



                  from itertools import chain

                  ...

                  for j in chain(range(0, 100, 1), range(100, 0, -1)):






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 5 at 14:19









                  blhsing

                  13.8k2628




                  13.8k2628







                  • 14




                    Generic unpacking creates a huge tuple with all integers materialised (remember that range() is a very lightweight object). Chaining is better!
                    – Martijn Pieters♦
                    Sep 5 at 14:22













                  • 14




                    Generic unpacking creates a huge tuple with all integers materialised (remember that range() is a very lightweight object). Chaining is better!
                    – Martijn Pieters♦
                    Sep 5 at 14:22








                  14




                  14




                  Generic unpacking creates a huge tuple with all integers materialised (remember that range() is a very lightweight object). Chaining is better!
                  – Martijn Pieters♦
                  Sep 5 at 14:22





                  Generic unpacking creates a huge tuple with all integers materialised (remember that range() is a very lightweight object). Chaining is better!
                  – Martijn Pieters♦
                  Sep 5 at 14:22











                  up vote
                  3
                  down vote













                  up = True # since we want to go from 0 to 100 first

                  while True: #for infinite loop

                  # For up == True we will print 0-->100 (0,100,1)
                  # For up == False we will print 100-->0 (100,0,-1)


                  start,stop,step = (0,100,1) if up else (100,0,-1)
                  for i in range(start,stop,step):
                  print(i)

                  up = not up # if we have just printed from 0-->100 (ie up==True), we want to print 100-->0 next so make up False ie up = not up( True)

                  # up will help toggle, between 0-->100 and 100-->0





                  share|improve this answer


















                  • 1




                    Pro tip for inverting a boolean: up ^= True
                    – wjandrea
                    Sep 6 at 0:58










                  • @wjandrea Yes thanks for commenting forgot to add as a side note, I was going to use it but then I thought to keep it simple in case OP was beginner.
                    – Tanmay jain
                    Sep 6 at 3:22














                  up vote
                  3
                  down vote













                  up = True # since we want to go from 0 to 100 first

                  while True: #for infinite loop

                  # For up == True we will print 0-->100 (0,100,1)
                  # For up == False we will print 100-->0 (100,0,-1)


                  start,stop,step = (0,100,1) if up else (100,0,-1)
                  for i in range(start,stop,step):
                  print(i)

                  up = not up # if we have just printed from 0-->100 (ie up==True), we want to print 100-->0 next so make up False ie up = not up( True)

                  # up will help toggle, between 0-->100 and 100-->0





                  share|improve this answer


















                  • 1




                    Pro tip for inverting a boolean: up ^= True
                    – wjandrea
                    Sep 6 at 0:58










                  • @wjandrea Yes thanks for commenting forgot to add as a side note, I was going to use it but then I thought to keep it simple in case OP was beginner.
                    – Tanmay jain
                    Sep 6 at 3:22












                  up vote
                  3
                  down vote










                  up vote
                  3
                  down vote









                  up = True # since we want to go from 0 to 100 first

                  while True: #for infinite loop

                  # For up == True we will print 0-->100 (0,100,1)
                  # For up == False we will print 100-->0 (100,0,-1)


                  start,stop,step = (0,100,1) if up else (100,0,-1)
                  for i in range(start,stop,step):
                  print(i)

                  up = not up # if we have just printed from 0-->100 (ie up==True), we want to print 100-->0 next so make up False ie up = not up( True)

                  # up will help toggle, between 0-->100 and 100-->0





                  share|improve this answer














                  up = True # since we want to go from 0 to 100 first

                  while True: #for infinite loop

                  # For up == True we will print 0-->100 (0,100,1)
                  # For up == False we will print 100-->0 (100,0,-1)


                  start,stop,step = (0,100,1) if up else (100,0,-1)
                  for i in range(start,stop,step):
                  print(i)

                  up = not up # if we have just printed from 0-->100 (ie up==True), we want to print 100-->0 next so make up False ie up = not up( True)

                  # up will help toggle, between 0-->100 and 100-->0






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Sep 5 at 16:59

























                  answered Sep 5 at 16:10









                  Tanmay jain

                  36915




                  36915







                  • 1




                    Pro tip for inverting a boolean: up ^= True
                    – wjandrea
                    Sep 6 at 0:58










                  • @wjandrea Yes thanks for commenting forgot to add as a side note, I was going to use it but then I thought to keep it simple in case OP was beginner.
                    – Tanmay jain
                    Sep 6 at 3:22












                  • 1




                    Pro tip for inverting a boolean: up ^= True
                    – wjandrea
                    Sep 6 at 0:58










                  • @wjandrea Yes thanks for commenting forgot to add as a side note, I was going to use it but then I thought to keep it simple in case OP was beginner.
                    – Tanmay jain
                    Sep 6 at 3:22







                  1




                  1




                  Pro tip for inverting a boolean: up ^= True
                  – wjandrea
                  Sep 6 at 0:58




                  Pro tip for inverting a boolean: up ^= True
                  – wjandrea
                  Sep 6 at 0:58












                  @wjandrea Yes thanks for commenting forgot to add as a side note, I was going to use it but then I thought to keep it simple in case OP was beginner.
                  – Tanmay jain
                  Sep 6 at 3:22




                  @wjandrea Yes thanks for commenting forgot to add as a side note, I was going to use it but then I thought to keep it simple in case OP was beginner.
                  – Tanmay jain
                  Sep 6 at 3:22










                  up vote
                  1
                  down vote













                  def up_down(lowest_value, highest_value):
                  current = lowest_value
                  delta = 1
                  while True: # Begin infinite loop
                  yield current
                  current += delta
                  if current <= lowest_value or current >= highest_value:
                  delta *= -1 # Turn around when either limit is hit


                  This defines a generator, which will continue to yield values for as long as you need. For example:



                  >>> u = up_down(0, 10)
                  >>> count = 0
                  >>> for j in u:
                  print(j) # for demonstration purposes
                  count += 1 # your other 100 lines of code here
                  if count >= 25: # your ending condition here
                  break


                  0
                  1
                  2
                  3
                  4
                  5
                  6
                  7
                  8
                  9
                  10
                  9
                  8
                  7
                  6
                  5
                  4
                  3
                  2
                  1
                  0
                  1
                  2
                  3
                  4





                  share|improve this answer
























                    up vote
                    1
                    down vote













                    def up_down(lowest_value, highest_value):
                    current = lowest_value
                    delta = 1
                    while True: # Begin infinite loop
                    yield current
                    current += delta
                    if current <= lowest_value or current >= highest_value:
                    delta *= -1 # Turn around when either limit is hit


                    This defines a generator, which will continue to yield values for as long as you need. For example:



                    >>> u = up_down(0, 10)
                    >>> count = 0
                    >>> for j in u:
                    print(j) # for demonstration purposes
                    count += 1 # your other 100 lines of code here
                    if count >= 25: # your ending condition here
                    break


                    0
                    1
                    2
                    3
                    4
                    5
                    6
                    7
                    8
                    9
                    10
                    9
                    8
                    7
                    6
                    5
                    4
                    3
                    2
                    1
                    0
                    1
                    2
                    3
                    4





                    share|improve this answer






















                      up vote
                      1
                      down vote










                      up vote
                      1
                      down vote









                      def up_down(lowest_value, highest_value):
                      current = lowest_value
                      delta = 1
                      while True: # Begin infinite loop
                      yield current
                      current += delta
                      if current <= lowest_value or current >= highest_value:
                      delta *= -1 # Turn around when either limit is hit


                      This defines a generator, which will continue to yield values for as long as you need. For example:



                      >>> u = up_down(0, 10)
                      >>> count = 0
                      >>> for j in u:
                      print(j) # for demonstration purposes
                      count += 1 # your other 100 lines of code here
                      if count >= 25: # your ending condition here
                      break


                      0
                      1
                      2
                      3
                      4
                      5
                      6
                      7
                      8
                      9
                      10
                      9
                      8
                      7
                      6
                      5
                      4
                      3
                      2
                      1
                      0
                      1
                      2
                      3
                      4





                      share|improve this answer












                      def up_down(lowest_value, highest_value):
                      current = lowest_value
                      delta = 1
                      while True: # Begin infinite loop
                      yield current
                      current += delta
                      if current <= lowest_value or current >= highest_value:
                      delta *= -1 # Turn around when either limit is hit


                      This defines a generator, which will continue to yield values for as long as you need. For example:



                      >>> u = up_down(0, 10)
                      >>> count = 0
                      >>> for j in u:
                      print(j) # for demonstration purposes
                      count += 1 # your other 100 lines of code here
                      if count >= 25: # your ending condition here
                      break


                      0
                      1
                      2
                      3
                      4
                      5
                      6
                      7
                      8
                      9
                      10
                      9
                      8
                      7
                      6
                      5
                      4
                      3
                      2
                      1
                      0
                      1
                      2
                      3
                      4






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Sep 6 at 5:23









                      mathmandan

                      440713




                      440713




















                          up vote
                          0
                          down vote













                          This is more of a partial answer than a direct answer to your question, but you can also use the notion of trigonometric functions and their oscillation to imitate a 'back and forth' loop.



                          If we have a cos function with an amplitude of 100, shifted left and upwards so that f(x) = 0 and 0 <= f(x) <= 100, we then have the formula f(x) = 50(cos(x-pi)+1) (plot of graph may be found here. The range is what you require, and oscillation occurs so there's no need to negate any values.



                          >>> from math import cos, pi
                          >>> f = lambda x: 50*(cos(x-pi)+1)
                          >>> f(0)
                          0.0
                          >>> f(pi/2)
                          50.0
                          >>> f(pi)
                          100.0
                          >>> f(3*pi/2)
                          50.0
                          >>> f(2*pi)
                          0.0


                          The issue of course comes in that the function doesn't give integer values so easily, thus it's not that helpful - but this may be useful for future readers where trigonometric functions might be helpful for their case.






                          share|improve this answer
























                            up vote
                            0
                            down vote













                            This is more of a partial answer than a direct answer to your question, but you can also use the notion of trigonometric functions and their oscillation to imitate a 'back and forth' loop.



                            If we have a cos function with an amplitude of 100, shifted left and upwards so that f(x) = 0 and 0 <= f(x) <= 100, we then have the formula f(x) = 50(cos(x-pi)+1) (plot of graph may be found here. The range is what you require, and oscillation occurs so there's no need to negate any values.



                            >>> from math import cos, pi
                            >>> f = lambda x: 50*(cos(x-pi)+1)
                            >>> f(0)
                            0.0
                            >>> f(pi/2)
                            50.0
                            >>> f(pi)
                            100.0
                            >>> f(3*pi/2)
                            50.0
                            >>> f(2*pi)
                            0.0


                            The issue of course comes in that the function doesn't give integer values so easily, thus it's not that helpful - but this may be useful for future readers where trigonometric functions might be helpful for their case.






                            share|improve this answer






















                              up vote
                              0
                              down vote










                              up vote
                              0
                              down vote









                              This is more of a partial answer than a direct answer to your question, but you can also use the notion of trigonometric functions and their oscillation to imitate a 'back and forth' loop.



                              If we have a cos function with an amplitude of 100, shifted left and upwards so that f(x) = 0 and 0 <= f(x) <= 100, we then have the formula f(x) = 50(cos(x-pi)+1) (plot of graph may be found here. The range is what you require, and oscillation occurs so there's no need to negate any values.



                              >>> from math import cos, pi
                              >>> f = lambda x: 50*(cos(x-pi)+1)
                              >>> f(0)
                              0.0
                              >>> f(pi/2)
                              50.0
                              >>> f(pi)
                              100.0
                              >>> f(3*pi/2)
                              50.0
                              >>> f(2*pi)
                              0.0


                              The issue of course comes in that the function doesn't give integer values so easily, thus it's not that helpful - but this may be useful for future readers where trigonometric functions might be helpful for their case.






                              share|improve this answer












                              This is more of a partial answer than a direct answer to your question, but you can also use the notion of trigonometric functions and their oscillation to imitate a 'back and forth' loop.



                              If we have a cos function with an amplitude of 100, shifted left and upwards so that f(x) = 0 and 0 <= f(x) <= 100, we then have the formula f(x) = 50(cos(x-pi)+1) (plot of graph may be found here. The range is what you require, and oscillation occurs so there's no need to negate any values.



                              >>> from math import cos, pi
                              >>> f = lambda x: 50*(cos(x-pi)+1)
                              >>> f(0)
                              0.0
                              >>> f(pi/2)
                              50.0
                              >>> f(pi)
                              100.0
                              >>> f(3*pi/2)
                              50.0
                              >>> f(2*pi)
                              0.0


                              The issue of course comes in that the function doesn't give integer values so easily, thus it's not that helpful - but this may be useful for future readers where trigonometric functions might be helpful for their case.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Sep 6 at 5:38









                              TerryA

                              41.6k87699




                              41.6k87699




















                                  up vote
                                  0
                                  down vote













                                  I had a similar problem a while ago where I also wanted to create values in the form of an infinite triangle wave, but wanted to step over some values. I ended up using a generator (and the range function as other also have been using):



                                  def tri_wave(min, max, step=1):
                                  while True:
                                  yield from range(min, max, step)
                                  yield from range(max, min, -1 * step)


                                  With carefully selected values on min, max and step (i.e. evenly divisible),



                                  for value in tri_wave(0, 8, 2):
                                  print(value, end=", ")


                                  I get the min and max value only once, which was my goal:



                                  ...0, 2, 4, 6, 8, 6, 4, 2, 0, 2, 4, 6, 8, 6, 4...


                                  I was using Python 3.6 at the time.






                                  share|improve this answer
























                                    up vote
                                    0
                                    down vote













                                    I had a similar problem a while ago where I also wanted to create values in the form of an infinite triangle wave, but wanted to step over some values. I ended up using a generator (and the range function as other also have been using):



                                    def tri_wave(min, max, step=1):
                                    while True:
                                    yield from range(min, max, step)
                                    yield from range(max, min, -1 * step)


                                    With carefully selected values on min, max and step (i.e. evenly divisible),



                                    for value in tri_wave(0, 8, 2):
                                    print(value, end=", ")


                                    I get the min and max value only once, which was my goal:



                                    ...0, 2, 4, 6, 8, 6, 4, 2, 0, 2, 4, 6, 8, 6, 4...


                                    I was using Python 3.6 at the time.






                                    share|improve this answer






















                                      up vote
                                      0
                                      down vote










                                      up vote
                                      0
                                      down vote









                                      I had a similar problem a while ago where I also wanted to create values in the form of an infinite triangle wave, but wanted to step over some values. I ended up using a generator (and the range function as other also have been using):



                                      def tri_wave(min, max, step=1):
                                      while True:
                                      yield from range(min, max, step)
                                      yield from range(max, min, -1 * step)


                                      With carefully selected values on min, max and step (i.e. evenly divisible),



                                      for value in tri_wave(0, 8, 2):
                                      print(value, end=", ")


                                      I get the min and max value only once, which was my goal:



                                      ...0, 2, 4, 6, 8, 6, 4, 2, 0, 2, 4, 6, 8, 6, 4...


                                      I was using Python 3.6 at the time.






                                      share|improve this answer












                                      I had a similar problem a while ago where I also wanted to create values in the form of an infinite triangle wave, but wanted to step over some values. I ended up using a generator (and the range function as other also have been using):



                                      def tri_wave(min, max, step=1):
                                      while True:
                                      yield from range(min, max, step)
                                      yield from range(max, min, -1 * step)


                                      With carefully selected values on min, max and step (i.e. evenly divisible),



                                      for value in tri_wave(0, 8, 2):
                                      print(value, end=", ")


                                      I get the min and max value only once, which was my goal:



                                      ...0, 2, 4, 6, 8, 6, 4, 2, 0, 2, 4, 6, 8, 6, 4...


                                      I was using Python 3.6 at the time.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered 2 days ago









                                      Amoork

                                      364




                                      364



























                                           

                                          draft saved


                                          draft discarded















































                                           


                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52187275%2fback-and-forth-loop-python%23new-answer', 'question_page');

                                          );

                                          Post as a guest













































































                                          Comments

                                          Popular posts from this blog

                                          What does second last employer means? [closed]

                                          List of Gilmore Girls characters

                                          Confectionery