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
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
Related Questions
Write a Python program using two functions area and perimeter to compute the area and perimeter of a rectangle. The program should take length and breadth of the rectangle as input from the user.
Assertion (A): Positional arguments in Python functions must be passed in the exact order in which they are defined in the function signature.
Reasoning (R): This is because Python functions automatically assign default values to positional arguments.
- Both A and R are true, and R is the correct explanation of A.
- Both A and R are true, and R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.