The code given below accepts a number as an argument and returns True if the number is prime, and False otherwise. Observe the following code carefully and rewrite it after removing all syntax and logical errors. Underline all the corrections made.

def is_prime(n):

  if n < 2:

  return False

  for i in range(2, n)

     if n % i = 0:

       return false

     else:

       return True

Answer:

Answer by student

Corrected code to accept a number as an argument and returns True if the number is prime, and False otherwise - Teachoo.png

Detailed answer by teachoo

The code given below accepts a number as an argument and returns True if the number is prime, and False otherwise. A prime number is a natural number that has exactly two factors, 1 and itself. To check if a number is prime, we can use a loop to iterate over all the possible factors from 2 to n-1 and see if any of them divides the number evenly. If yes, then the number is not prime and we can return False. If no, then the number is prime and we can return True.

The rest of the post is locked. Join Teachoo Black to see the full post.

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.