1

Right now I have a script that is meant to loop forever. However, I would like to do something different on the first 'lap' along the lines of the following:

import math

for i in range(0,math.inf):
    if i == 0:
       print("I'm gonna start the first lap")
    print('this is one lap')

"I'm gonna start the first lap"
'this is a lap'
'this is a lap'

Note that this code does not work because math.inf is a float, NOT an integer. And this post here says that in Python there is no way to represent infinity as an integer.

Using while True: could make sense in this situation, but is there any way to get the function to print something different for first (or the xth) repetition for that matter?

lespaul
  • 477
  • 2
  • 8
  • 21
  • 2
    if you need a potentially infinite integers generator -- take a look at [`itertools.count`](https://docs.python.org/3/library/itertools.html#itertools.count) – Azat Ibrakov Jul 06 '18 at 10:07

4 Answers4

3
print("I'm gonna start the first lap")
while True:
    print('this is one lap')

Put it before the loop.

Nikita Utkin
  • 78
  • 2
  • 8
2

If you wish to use an infinite for loop while keeping a counter, you can use itertools.count:

from itertools import count

for i in count():
    if i == 0:
        print("I'm gonna start the first lap")
    print('This is one lap')
    # break
jpp
  • 159,742
  • 34
  • 281
  • 339
0

The obvious way to do that is to put first iteration before the loop:

print("I'm gonna start the first lap")
while True:
   print('this is one lap')

But, this example does not specify rest of the problem.

0

Just count the laps and compare the current lap with the desired lap. For the xth repetition:

counter = 0
while True:
    if counter == xth:
        print("This is the xth lap")
    print('this is one lap')
    counter += 1
Poshi
  • 5,332
  • 3
  • 15
  • 32