Is_Prime


#1

So im kind of confused as to why the scope on this changes the outcome.

If I run this code:

def is_prime(x):
    
    if x < 2:
        return False
    elif x == 2 or x == 3:
        return True
    for n in range(2, x-1):
        if x % n == 0:
            return False
    else:    
        return True

it works properly, but if i run this code:

def is_prime(x):
    
    if x < 2:
        return False
    elif x == 2 or x == 3:
        return True
    for n in range(2, x-1):
        if x % n == 0:
            return False
        else:    
            return True

it fails to work right. The only difference being the scope of the else statement at the bottom.

I dont understand why this is happening.


#2

your function returns what it says in the first return-statement that is executed:

def test(a):
    if a > 2:
        return True
    if a > 5:
        return False

test returns True if a is ten.

In the code above, "else: return True" is only executed if you run through the loop every time without returning False. So every number between 1 and x must fulfill the condition.

In the code below, "else: return True" is executed when the if-statement is not. So, if a number is not dividable by 2 (the first number you test) the function returns True.

i hope this helps


#3

why so complicated?
def is_int(x):
if x % 2 == 1 or x % 2 == 0:
return True
else:
return False

print is_int(7.3)


#4

try this
def is_prime(x):
if x < 2:
return False
elif x == 2 or x == 3:
return True
elif x % 2 == 0:
return False
i = 3
while i * i <= x:
if x % i == 0:
return False
i += 2
return True

a number is a prime doesn't mean it should be an odd number or even number.