Wednesday 20 May 2015

Python 3 - Use In For In Range Loop To Do Differently Occurring Tasks

Problem

I wanted a fast way to run through an operation in a loop and then to do another operation, say every fifth time in Python 3.
You can run a loop in a certain range quite easily:

count = 1
for i in range (0,20):
print(count)
count += 1
This would reveal a list of numbers from 1 - 20 one under the other.
I knew that this was what I wanted to do but how could I print print ("ping") every fifth number (eg after,0,5,10,15,20)
My first direction was to use the step option in range which you can add to the end of your arguments:

count = 1
for i in range (0,20,5):
print(count)
count += 1
This would display:
1
2
3
4

The operation will loop through 20 times but every fifth time (step) the operation will print a number.
Not what I had in mind but useful.

Solution

The solution turned out to be fairly simple:

What I did was use two loops. One nested in the other. The first one printed the "ping". The nested loop counted through the numbers.
If I wanted the "ping" printed after every 5th time in a range of 20 it would occur 4 times (20/5 = 4). So I set the "ping" for loop for the to start at 0 and end at 4.
In the nested for loop I run the loop to 5 adding 1 to the count.
Now when the "ping" loop is run the first time it prints "ping" and counts from 1-5. The second time the "ping" loop runs it prints "ping" again and counts from 6-10.
This will continue until after the "ping" loop runs it's last loop at 4.

Applications

This might be useful for adding a note or a warning after a certain amount of data iterates through.
In a simple shooting game you might want to shoot a number of times before a rocket is launched if the fire key is still depressed. 

No comments:

Post a Comment