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:
- The first
ifstatement should be indented properly inside the function. - The
forloop is missing a colon (:) at the end of its definition. - In the second
ifcondition, the code uses the assignment operator=instead of the equality operator==to checkif n % iis equal to 0. - In Python,
Falseis a boolean keyword, and it must be capitalized. The code usesfalse(lowercase) in theforloop, 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
2 Likes