I am struggling to understand the modulus part of this code.
I am trying to ONLY print the num when the modulus is 0, that is to say it’s an even number. If I set number as 100 and rate as 1.5 I’ll get results. However, if I change the rate value to anything other than .25 .5 .75 I get nothing returned.
Here’s an example: If I use 100 as the number and 1.4 as the rate I should get 7.14.21 etc returned as 1.4 goes into these numbers evenly. However, it doesn’t output.
Initial searches tells me modulus won’t work for decimals yet it does for .5 increments.
Any input greatly appreciated.
def findnum(number, rate): for num in range(pinumber): if num %(rate) == 0: if num != 0: print(num)
When deviding with decimal numbers, there is always the problem of precision errors. That means, that
7 % 1.4 isn’t
4.440892098500626e-16, for your code to work you must use the
decimal module whitch stores the numbers as strings.
from decimal import Decimal def findnum(number, rate): for num in range(number): if num % Decimal(str(rate)) == 0: if num != 0: print(num)