Function Errors in Python and How to Fix Them

This Python function fun(n) checks if a number is prime by testing divisibility starting from 3 up to the square root of the number. It returns True for prime numbers and False for non-prime numbers.

Error Code

 codedef fun(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r = 3
while r * r <= n: # Incorrect indentation here, causing the error
if n % r == 0:
return False
r += 2
return True # This line is also misplaced, leading to an error
print(is_prime(78), is_prime(79)) # is_prime is called but the function is named fun

def fun(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r = 3
while r * r <= n: # Same incorrect indentation in this block
if n % r == 0:
return False
r += 2
return True # Same issue as before
print(is_prime(78), is_prime(79)) # Again, the function should be fun, not is_prime

Correct Python code:

codedef is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r = 3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True

print(is_prime(78), is_prime(79))

Explanation of the Code

The function is_prime(n) checks whether a given number n is prime or not. Here’s a breakdown of how the function works:

  • Checking Special Cases:
    The numbers 2 and 3 are prime, so if n is either 2 or 3, the function immediately returns True.
  • Handling Non-Prime Numbers:
    The number 1 is not prime, and any even number greater than 2 is also not prime. So, if n is 1 or an even number, the function returns False.
  • Checking Odd Numbers:
    Starting from r = 3, the function checks only odd numbers up to the square root of n. This optimization reduces the number of checks needed to determine whether n is prime. If n is divisible by any odd number r, it is not prime, and the function returns False. Otherwise, if no divisors are found, the function returns True, indicating that n is a prime number.

Common Coding Error Fixed

The main issue in the original code was the indentation of the while loop. Python requires proper indentation for the structure of the code, and since the loop was not properly indented, it caused an error. The corrected version ensures that the while loop and its contents are part of the function body by indenting them correctly.

Additionally, the original code used print(is_prime(78), is_prime(79)), but the function was named fun. To maintain clarity and avoid confusion, I renamed the function to is_prime() in both the function definition and the print statement.

Related blog posts