Can you do is_prime without a variable to store the True and False?


#1




I stayed on this exercise for about 30 mins before going to the forums. I discovered the fact that once a return statement is stated the loop ends. This forced me to use a variable to store True or False and then after return the variable. I was wondering if there was a way to do this without using a variable to store True and False. From what I know you can't, but I am new to coding, so I have no idea. Anybody know a way?


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


#2

You bet.

The idea is--
Use your for-loop to check for either the true condition or the false condition. If you find it, return with true/false according to what you were searching for.
That way, if you arrive at code after the for loop, you know for sure the condition you were checking for in the for loop never happened, so after the for loop simply return the opposite of inside the for loop

It does depend on the problem though. For odd/even sure we can do this, but sometimes you might need a variable or some other way of storing stuff.
I'm coming from C and Assembly so I approach these a bit different than some people...!


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.