1

I wrote some code to evaluate the integers between x and y and check for divisibility by the integers 3 and 5. This is the code.

def div_3_5(start, end):
    result = 0
    result2 = 0
    result3 = 0 
    while start < end:
        result2 = start + result 
        result = result2 - start + 1
        if result2 % 3==0 or 5==0:
            result3 = result3 + 1 
        else:
            result3 = result3 + 0
        return result3

I'm just a beginner but everything seems fine in the code of course unless I have used the "or" statement incorrectly or checked for divisibility incorrectly. Which brings me to the main question. Any help would be appreciated.

saf
  • 15
  • 1
  • 1
  • 4

1 Answers1

6

You need to do this:

if result2 % 3 == 0 or result2 % 5 == 0:

Otherwise it is parsed as if (result2 % 3==0) or (5==0):, which is clearly wrong as 5 != 0.

Another suggestion which can be quite useful as you have more numbers you want to check for divisibility:

if any(result2 % i == 0 for i in (3, 5)):

This is a much simpler version of what you seem to be trying to do (Project Euler problem 1):

def div_3_5(start, end):
    return sum(1 for i in range(start, end+1) if i % 3 == 0 or i % 5 == 0)

Or, using De Morgan's laws and the fact that 0 is a False-ish value:

def div_3_5(start, end):
    return sum(1 for i in range(start, end+1) if not (i % 3 and i % 5))
Volatility
  • 31,232
  • 10
  • 80
  • 89
  • +1 for ninja'ing. Sometimes, Python can be a little bit *too* English; you've got to remember that Python will not read your mind. – Sean Allred Mar 09 '13 at 11:50