Errors and Exceptions in Python

Last Updated : 29 May, 2026

Errors are problems in a program that causes the program to stop its execution. On the other hand, exceptions are raised when some internal events change the program's normal flow. 

Syntax Errors

A syntax error occurs when the code does not follow Python’s writing rules. Python detects these errors before running the program and shows the location of the mistake.

Example: In this example, the code gives a syntax error because the colon (:) is missing after the if statement.

Python
a = 10000 
if a > 2999
    print("Eligible")

Output

Output3467
Syntax error

Indentation Error

Python uses indentation (spaces or tabs at the beginning of a line) to define blocks of code. An IndentationError occurs when the indentation is missing or incorrect.

Example: Here, the code gives an IndentationError because the statement inside the if block is not indented properly.

Python
if a<3:
print("gfg")

Output

Output
Indentation Error

Logical Errors

Logical errors are mistakes in the program logic that cause incorrect output even though the code runs successfully. The program does not crash, but the result is different from what was expected.

  • Code runs without any syntax errors.
  • Program produces incorrect or unexpected output.
  • These errors are harder to find because no error message is shown.
  • They usually happen due to wrong formulas, conditions or calculations.

Example: In this example, the program calculates the average incorrectly because 1 is subtracted from the final result.

Python
a = [10, 20, 30, 40, 50]
b = 0

for i in a:
    b += i

res = b / len(a) - 1
print(res)

Output
29.0

Explanation: expected average of the list is 30, but the program prints 29.0. The error happens because 1 is subtracted from the result. The correct formula should be res = b / len(a)

Errors vs Exceptions

Errors and exceptions are both problems in a program, but they occur in different situations.

  • Error: Problems in the code such as SyntaxError that prevent the program from running correctly.
  • Exception: Problems that occur while the program is running, such as division by zero or missing files. Exceptions can be handled using exception handling.

Example: In this example, the first part contains a syntax error, while the second part causes a runtime exception.

Python
# Syntax Error
print("Hello world"   # Missing closing parenthesis

# Exception
n = 10
res = n / 0

Explanation: The syntax error stops the program before execution starts because the closing parenthesis is missing. The ZeroDivisionError occurs during execution when a number is divided by zero.

Comment