Errors and Exceptions in Python

Last Updated : 18 Mar, 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 in Python

Syntax error occurs when the code doesn't follow Python's rules, like using incorrect grammar in English. Python stops and points out the issue before running the program.

Example 1: In this example, this code returns a syntax error because there is a missing colon (:) after the if statement. The correct syntax requires a colon to indicate the start of the block of code to be executed if the condition is true.

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

Output

Output3467
Syntax error

Indentation Error

Python uses indentation to define blocks of code. An IndentationError occurs when the required indentation is missing or incorrect.

This code returns an IndentationError because Python expects an indented block after the if statement, but the statement inside the block is not properly indented.

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

Output

Output
Indentation Error

Python Logical Errors (Exceptions)

Logical errors are subtle bugs in the program that allow the code to run but produce incorrect or unintended results. These are often harder to detect since the program doesn’t crash, but the output is not as expected.

Characteristics of Logical Errors

  • No Syntax Error: The code runs without issues.
  • Unexpected Output: The results produced by the program are not what the programmer intended.
  • Difficult to Detect: These errors can be tricky to spot since there’s no obvious problem with the code itself.
  • Causes: Faulty logic, incorrect assumptions, or improper use of operators.

Example:

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 output is that the average of a should be 30, but the program outputs 29.0. The logical error occurs because the formula b/ len(a) - 1 incorrectly subtracts 1, leading to an incorrect result. The correct formula should be b / len(a).

Common Built-in Exceptions

Some common built-in exceptions other than above mention exceptions are:

ExceptionDescription
IndexErrorWhen the wrong index of a list is retrieved.
AssertionErrorIt occurs when the assert statement fails
AttributeErrorIt occurs when an attribute assignment is failed.
ImportErrorIt occurs when an imported module is not found.
KeyErrorIt occurs when the key of the dictionary is not found.
NameErrorIt occurs when the variable is not defined.
MemoryErrorIt occurs when a program runs out of memory.
TypeErrorIt occurs when a function and operation are applied in an incorrect type.

Note: For more information, refer to Built-in Exceptions in Python 
To understand Python exception handling, refer to Python Exception Handling

Comment