6/15 is_prime Why is this wrong?


#1

def is_prime(x):
for i in xrange(2, x - 1):
if x % i == 0 or x < 2:
return False
return True

print is_prime(7)

for some reason when is_prime(0) is executed it returns True? I thought my or statement takes care of this issue. I know I can specify that x cannot equal 0, but I feel like it is unnecessary space. Can someone explain why my or statement does not work?


#2

0 % 2    ->    0


#3

Yeah I understand that, so why does it return True?


#4

Oh.. ehm

Well here's next one then:

<any bool> or True      ->      True

#5

oh ok so a False or True returns True. Totally forgot about that, thanks.


#6

Nope that was wrong too.

Here we go: How many times does your loop iterate?


#7

I totally blame your lack of formatting. Totally. 'TIS ALL YOUR FAULT.

Sorry.


#9

yeah I don't really know how to format on here.Also it starts at 2 and reiterates until it reaches x - 1.


#10

And when x is 0?

Check out the buttons in the post editor


#11

ah ok i see the error. Thanks!


#12

Sorry again for misleading you, thought I spotted the problem and didn't actually think about whether that was it.

The way you could have found this, other than staring at it, was to have inserted print statements in your code to print out what the program was doing step by step