Determining if a number evenly divides by 25, Python

Go To StackoverFlow.com

6

I'm trying to check if each number in a list is evenly divisible by 25 using Python. I'm not sure what is the right process. I want to do something like this:

n = [100, 101, 102, 125, 355, 275, 435, 134, 78, 550]
for row in rows:

    if n / 25 == an evenly divisble number:
        row.STATUS = "Major"
    else:
        row.STATUS = "Minor"

Any suggestions are welcome.

2012-04-04 20:42
by Mike
Is n meant to be a list, as shown, or an integer - BlueRaja - Danny Pflughoeft 2012-04-04 21:08


17

Use the modulo operator:

for row in rows:
    if n % 25:
        row.STATUS = "Minor"
    else:
        row.STATUS = "Major"

or

for row in rows:
    row.STATUS = "Minor" if n % 25 else "Major"

n % 25 means "Give me the remainder when n is divided by 25".

Since 0 is Falsey, you don't need to explicitly compare to 0, just use it directly in the if -- if the remainder is 0, then it's a major row. If it's not, it's a minor row.

2012-04-04 20:44
by agf
I've always found this syntax confusing. if n % 25: reads like "if n is divisible by 25" rather than the other way around. But that's just me - NullUserException 2012-04-04 20:49
@NullUserException That's why I explained it :) Just get used to reading it as "If n has a remainder when divided by 25" - agf 2012-04-04 20:50
Thanks a lot agf! You're quick on the response. It's much appreciated. You gave me exactly what iw as looking for! Cheers - Mike 2012-04-04 21:27


13

Use the modulo operator to determine the division remainder:

if n % 25 == 0:
2012-04-04 20:44
by Sven Marnach
Thanks for the response Sven - Mike 2012-04-04 21:28
Ads