KnowledgeBoat Logo
|

Computer Science

Identify the errors from the code below.

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

Python Functions

1 Like

Answer

The first if statement should be indented inside function correctly; Missing colon at the end of the for loop; '=' should be replaced with '==' in the second if condition; false should be capitalized to False in for loop;

Reason — The errors in the code are as follows:

  1. The first if statement should be indented properly inside the function.
  2. The for loop is missing a colon (:) at the end of its definition.
  3. In the second if condition, the code uses the assignment operator = instead of the equality operator == to check if n % i is equal to 0.
  4. In Python, False is a boolean keyword, and it must be capitalized. The code uses false (lowercase) in the for loop, which is incorrect.

The corrected code is:

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

Answered By

3 Likes


Related Questions