Page 306 - Artificial Intellegence_v2.0_Class_9
P. 306

Operator Precedence


        An expression is made up of values, variables, operators and functions. For example,
                   x-5+6 is an expression

        To evaluate an expression with multiple operators Python follows an order of precedence. This order can be
        altered by writing an expression within parenthesis.
        The order of precedence in the descending order is listed below:

                               Order of Precedence                    Operators
                                         1               ()
                                         2               **
                                         3               */%//
                                         4               +-
                                         5               <= < > >=
                                         6               == !=
                                         7               = %= /= //= -= += *= **=
                                         8               not, and, or

        If an expression contains two or more operators with the same precedence, then order of evaluation is from left
        to right except for exponential (**) which is always from right to left. For example,
           • 10 – 2 + 3 – 3 will be evaluated from left to right as + and – has the same order of precedence. So, the answer
           will be 10 – 2 will be 8 + 3 will be 11 – 3 will be 8.
           • 2  **  3  **  2  will  always  be  evaluated  from  right  to  left.  It  will  be  calculated  as  2  **  (3  **  2)  and  not  as
           (2 ** 3) ** 2. So, the answer will be 512.


                         Task



             Solve the following expressions using the operator precedence:
             •  10 + 20 / 5 – 3 * 2

             •  5 * (10 + 5) + 10 – 5




                 Comments in Python

        Comments are used to increase the readability of the code. We use them to give proper understanding of the
        code in simple English statements. They are completely ignored by the Python interpreter. It is always a good
        practice to add comments in your code so that if anybody in future wish to understand or modify your code,
        then through comments it will be easy to interpret the instructions. There are two different ways of writing
        comments in Python. Let us learn about them in detail.

        Single Line Comment

        Single line comment starts with hash symbol # followed by the text to be written as a comment that lasts till the
        end of the line.


              304     Touchpad Artificial Intelligence (Ver. 2.0)-IX
   301   302   303   304   305   306   307   308   309   310   311