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.
The code provided below is intended to swap the first and last elements of a given tuple. However, there are syntax and logical errors in the code. Rewrite it after removing all errors. Underline all the corrections made.
def swap_first_last(tup) if len(tup) < 2: return tup new_tup = (tup[-1],) + tup[1:-1] + (tup[0]) return new_tup result = swap_first_last((1, 2, 3, 4)) print("Swapped tuple: " result)