Page 309 - Artificial Intellegence_v2.0_Class_9
P. 309

Let us create the preceding program again by using the int( ) function.

              a = int(input("enter first number"))                   #line 1
              b = int(input("enter second number"))                  #line 2
              c = a + b

              print("the sum is", c)
            Now, the program will display the correct output as 9.


                    Errors in Python

            Sometimes, while writing a code we might make mistakes. These mistakes are called errors. There are three kinds
            of errors which a programmer encounters in Python: syntax error, logical error and runtime error. Let us learn
            about them in detail.

            Syntax Error

            Syntax means writing the code following the rules of Python language. Syntax error is occurred when we violating
            the rules of Python language. This is the most common type of an error made by a programmer. If there is typing
            error, incorrect indentation, or incorrect arguments given in a function then Python will not be able to interpret
            the instruction and will raise a syntax error. In IDLE, it will be highlighted by an arrow and then you can go to
            that line to rectify the error. Some of the examples of syntax error are:

              a + b = c
              SyntaxError: cannot assign to operator
              myname = Arshia
              SyntaxError: EOL while scanning string literal
              a = 5
              b = 10
                c = a + b
              SyntaxError: unexpected indent
              print("Python"))
              SyntaxError: unmatched ')'
            Logical Error

            This kind of error is difficult to find since the program will run correctly but the desired output is not achieved.
            This happens if we give a wrong formula for the calculation to be done, write wrong logic for the problem to be
            solved through the code. For example,
            To calculate the average:

              p = marks1 + marks2 / 2  #instead of (marks1+marks2) / 2
            Preceding code produces a wrong output due to the logical error in formula. Let us take another example. To
            find the perimeter of rectangle,

              p = 2 * l + b            #instead of p = 2 * (l + b)

            Runtime Error
            Runtime error occurs during the execution of a program like wrong input or output errors, undefined object
            errors, division by zero errors. This type of error will halt the program execution unexpectedly.
            Example of runtime error is:
              a = int(input("enter first number"))
              b = int(input("enter second number"))
              c = a / b
                                                                                   Introduction to Python  307
   304   305   306   307   308   309   310   311   312   313   314