Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to do something once a loop has repeated a desired amount

This is a pretty short and not so useful tutorial by the way!
So I have some projects where I have animations like

``````g=0
for i in range(1,10):#Repeats 10 times
print(Fore.RED+"Hi!")
time.sleep(1)
os.system('clear')
print(Fore.BLUE+"Hi!")
time.sleep(1)
os.system('clear')``````

Sometimes I add something to the end that occurs every 2nd time the loop repeats, like this:

``````g+=1
if g==3:
g=0
print("\a",end="")``````

I thought this was a bit much, and quite frankly I don't like looking at it. It was a lot of useless stuff, or at least how I saw it, it looked like it could be improved. I made another way to do this, and it uses basic math! Less lines of code, and I like it a lot better.

# The Old Way

The old way I did this was displayed above. In this, i have the variable g, and each time it repeats g gets added one. If g reaches 3, aka it has repeated 3 times, i reset the variable to 0 and do whatever i need to do. Pretty easy.

# The New Way

This is my new way of doing this

``````x+=1
if x/3 in range(1,100):
print("\a",end="")``````

It might seem confusing, but listen. It uses the same concept, with a variable getting plus one every time it repeats. The event will happen every 3rd time. If you wanted to it to happen every 4th time, just replace `x/3` with `x/4`, and so on.
Think about this, range() only does whole numbers, so it excludes decimals. `x/3` Checks to make sure that the number of times repeated is a multiple of three. if it is the first time, the number will be 1/3, which is .33 which is not in the range. 2nd time, 2/3, .66, still not in the range. 3rd time, 3/3, 1, now this is in the range. So the event will happen.

Using this, we never really have to refresh the variable, we can just make the range() 1 through like a trillion. Then your code will only fail if they repeat it a trillion times, not likely. One the 6th, 9th, 12th, 15th, and so one times the code repeats, it will do the event. Not only is it less lines of code, it looks better. Hope this helps some of you, comment any questions!