Modulos in Python
Modulos in Python are super useful. They can we be used when we don’t want to print a check each pass during a loop. For example, if I’m looping through 100,000 numbers and want to get an update of how my automation is going every so often instead of printing each loop or blindly running through 100k iterations then we could use modulos in python.
import numpy as np # This creates an random array with 100,000 elements from 0 to 99 random_array = np.random.randint(100, size=100000) i=0 # Here we loop through the array and do some sort of check or task for number in random_array: i=i+1 # This is where the magic is happening if i%25000==0: print('We are at number '+str(i)) if number == 101: print('This will never happen')
Modulo gives us the remainder left over when we divide one number by the next. Because all integers are divisible by 1 then any number modulo 1 is going to be 0. In relation to the above example, 25,000 is divisible by 25,000 and 50,000 is divisible cleanly by 25,000 so we’ll print in both cases. Next comes 75k and finally 100k. So, we’ll ultimately print four times during the duration of the script to be kept up to date on the progress.
If you’re having issues with your Python installation check out this article. If you’re looking for something a little meatier then check out my dumbed down explanation of lambdas here. If you don’t like how I write then check out the latest Python docs here. Happy coding!