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.
Types of Errors in Python
Python errors are mainly divided into three types:
- Syntax Errors
- Runtime Errors
- Logical Errors
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
ifstatement is missing a colon:. - Python cannot interpret the code.
- The program stops before execution starts.
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
ZeroDivisionErrorduring execution.
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.
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
Difference Between Error and Exception
- Error → A problem that stops normal program execution
-
Exception → A runtime error that can be handled using
try-except