Errors in Python

Errors in Python are problems in a program that prevent it from running correctly or producing the expected output.

Errors usually occur due to wrong syntax, logic mistakes, or unexpected situations during execution.

What is an Error?

An error is a mistake in a program that causes it to stop execution or behave incorrectly.

Article Algo

Types of Errors in Python

Python errors are mainly divided into three types:

  • Syntax Errors
  • Runtime Errors
  • Logical Errors

Article Algo

1. Syntax Errors

A syntax error occurs when Python does not understand the code because it is written incorrectly and does not follow Python’s rules.

Example

if x > 5 print("Hello")

Explanation

  • The if statement is missing a colon :.
  • Python cannot interpret the code.
  • The program stops before execution starts.

Article Algo

2. Runtime Errors

A runtime error occurs while the program is running, even though the syntax is correct.

Example

print(10 / 0)

Explanation

  • The code syntax is correct.
  • Division by zero is not allowed.
  • Python raises a ZeroDivisionError during execution.

Article Algo

3. Logical Errors

A logical error occurs when the program runs without crashing but produces incorrect output due to wrong logic.

Example

a = 10 b = 5 print(a - b) # Expected addition

Explanation

  • The program runs successfully.
  • The logic is wrong because subtraction is used instead of addition.
  • The output is incorrect but no error message appears.

Article Algo

Common Runtime Errors in Python

  • ZeroDivisionError → Dividing a number by zero
  • ValueError → Invalid value type
  • TypeError → Operation on incompatible data types
  • IndexError → Accessing an index that does not exist
  • KeyError → Accessing a missing dictionary key
  • NameError → Using an undefined variable

Article Algo

Difference Between Error and Exception

  • Error → A problem that stops normal program execution
  • Exception → A runtime error that can be handled using try-except

Article Algo