Page 168 - Computer Science Class 11 Without Functions
P. 168
7.9.2 Logical Errors
A logical error does not give the desired output, even though there is no syntax error in the program. Such errors are
sometimes difficult to identify as all the statements in the program are executed successfully. When a logical error
is encountered, often it helps to work backward by examining the output produced by the program and look for the
cause of error.
For example, to calculate the percentage of marks obtained by a student, the expression should be
percentage = marksObtained/maxMarks * 100
However, if the programmer writes the formula as
percentage = maxMarks/marksObtained * 100
the statement being syntactically correct, will be executed but it will not give the correct output.
7.9.3 Runtime Errors
As the name suggests, a runtime error occurs during the execution of the program. The statement is syntactically
correct but cannot be executed by the interpreter. For example, while executing the statement
result = numerator/denominator
if the value of denominator is 0 (zero), it will result in a runtime error (division by zero). Similarly, a runtime error will
be generated, if the user enters a string instead of a number. Program 7.2 below illustrates the runtime error.
Program 7.3 Write a program to compute quotient of two numbers.
01 # Objective: To compute quotient of two numbers
02 # To understand runtime errors.
03 #User inputs: numeric values for numerator and denominator
04 numerator = int(input("Enter the numerator : "))
05 denominator = int(input("Enter the denominator : "))
06 quotient = numerator/denominator
07 print("The quotient is : ", quotient)
Sample Output 1: When the user enters denominator as 0
>>> Enter the numerator : 40
>>> Enter the denominator : 0
Traceback (most recent call last):
File "C:/Users/ADMIN/quotient.py" line 4, in <module>
quotient = numerator/denominator
ZeroDivisionError: division by zero
Sample Output 2: When the user enters numerator as a string that cannot be interpreted as an int
>>> Enter the numerator : 23*23
Traceback (most recent call last):
File "C:/Users/ADMIN/quotient.py" line 2, in <module>
numerator = int(input("Enter the numerator : "))
ValueError: invalid literal for int() with base 10: '23*23'
Sample Output 3: When the user enters suitable values
>>> Enter the numerator : 20
>>> Enter the denominator : 5
The quotient is : 4.0
Below, we give some more examples of runtime errors:
>>> print(x)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
print(x)
NameError: name 'x' is not defined
166 Touchpad Computer Science-XI

