Is_prime: (last line "return True" logic) help me undestand!


#1

https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096

why the code is right if only i write "return True" after if/else constraction, as bellow ?

def is_prime(x):
    
    if x > 1:
        for i in range(2,x):
            if x%i==0:
                return False

    else:
        return False
    
    
    return True

but if i write other code, with "return True" in if/elif/else constaction (as bellow) - it doesn't work!

def is_prime(x):
    
    if x > 2:
        for i in range(2,x):
            if x%i==0:
                return False
                
            else: 
                return True
                
    
    elif x < 2:
        return False
    
    else:
        return True

i just wont to try Python logic in my first code aboun last line "return True"

why it return False, in total ? if last line "return True"

>>>>return False
return True

for example, is_prime(9)


#2

because when you write else here:

     elif x < 2:
        return False
    
    else:
        return True

else will on run for x=2, else only runs when if and elif condition evaluate to false

and in your loop:

        for i in range(2,x):
            if x%i==0:
                return False
                
            else: 
                return True

a return keyword (which causes the function to end) will be reached in the first iteration, causing the loop to break, which is not desired for finding prime number (given the whole loop needs to finish running in order for a number to a prime number)


#3

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