Prime number


#1



def is_prime(num):
    if num > 1:
      for i in range(2,num):
          if (num % i) == 0:
             
             break
          else:
             print(num,"is a prime number")
             return True
       
    elif n==2:
       return True
        
    else:
       print(num,"is not a prime number")
       return False
#please help me in correcting this code


Replace this line with your code.


#2

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

         break
      else:
         print(num,"is a prime number")
         return True

elif n==2:
   return True

else:
   print(num,"is not a prime number")
   return False

#3

here:

elif n==2:

where is n defined?

but the biggest problem is where many people struggle. A function ends the moment a return keyword is reached

so in the first run of your loop either the loop breaks, or True is returned and the function ends

you only want to return True after the for loop has finished running successfully (this is the condition for a number to be a prime number

this:

elif n==2:
   return True

will not work, because when num=2, the if condition (num > 1) is already true, when the if condition is true, elif and else won't run


#4

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

         break
      else:
         print(num,"is a prime number")
         return True

elif num==2:
   return True

else:
   print(num,"is not a prime number")
   return False

#5

again same problem is comming


#6

I was spotted more mistake and was editing my answer, did you read it all?


#7

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