Site icon FSIBLOG

Function Errors in Python and How to Fix Them

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:

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.

Exit mobile version