Page 459 - ComputerScience_Class_11
P. 459
Output
Pranya scored 99 marks in the test.
12.3 UNDERSTANDING ERRORS IN PYTHON
Errors are an inevitable part of programming. Instead of avoiding them, it's important to learn how to read and
understand error messages. These messages are key to debugging your code. Python's error messages provide a
traceback, which shows the error type, a description and the exact line number where the error occurred. Errors in
Python are broadly classified into three types: Syntax Errors, Runtime Errors and Logical Errors.
12.3.1 Syntax Errors
Syntax errors, also known as parsing errors, are the most basic kind of error. They occur when the Python interpreter
encounters code that violates the grammatical rules of the Python language. The interpreter cannot understand your
instructions, so the program fails before it even starts running. Common causes include:
• Forgetting a colon (:) at the end of an if, for, while or def statement.
• Missing or mismatched parentheses (), brackets [] or quotes "".
• Incorrect indentation (mixing tabs and spaces or inconsistent indentation levels).
• Misspelling Python keywords (e.g., writing whille instead of while).
Example: A syntax error (wrong quotes)
age = int(input("Enter your age: '))
print("In five years, you will be " + age + 5)
Error Message:
12.3.2 Run-Time Errors
Run-time errors, also known as exceptions, occur while the program is running. The syntax of the code is correct, so the
program starts, but during execution, something unexpected happens that forces the program to stop. These errors
are often caused by user input or unforeseen states.
The following table outlines some common types of run-time errors:
Error Type Description Example
ValueError Occurs when a function receives an argument of int("abc")
the correct type but an inappropriate value.
NameError Occurs when you try to use a variable or function print(age) (if age was never assigned
that has not been defined. a value)
TypeError Occurs when you try to perform an operation on "hello" / 5
a data type that doesn't support it.
ZeroDivisionError Occurs when you try to divide a number by zero. result = 10 / 0
IndexError Occurs when you try to access an element from my_list = [1,2,3]; print(my_
a list or tuple using an index that is out of range. list[5])
Data Processing in Python 457

