Page 481 - ComputerScience_Class_11
P. 481

12.5.1 Evaluation of the Expressions Involving the Operators
                 An expression in Python is a combination of variables, constants and operators that produces a value. When an expression
                 contains  more than  one  operator, Python  evaluates it  according  to  operator precedence  and  associativity rules.
                 Operator precedence decides which operator is evaluated first, while associativity decides the direction of evaluation
                 (left to right or right to left) when operators have the same precedence.
                 Program 15: To demonstrate operator precedence in Python.

                     Program 15.py

                  File  Edit  Format   Run   Options   Window     Help

                  # Arithmetic operators with precedence
                  result1 = 10 + 5 * 2
                  # First multiplication (5 * 2 = 10)
                  # Then addition (10 + 10 = 20)

                  # Using parentheses to change precedence
                  result2 = (10 + 5) * 2
                  # First parentheses (10 + 5 = 15)
                  # Then multiplication (15 * 2 = 30)

                  # Exponentiation (right to left associativity)
                  result3 = 2 ** 3 ** 2
                  # First 3 ** 2 = 9
                  # Then 2 ** 9 = 512

                  # Floor division and modulus
                  result4 = 17 // 3 + 17 % 3
                  # Floor division (17 // 3 = 5)
                  # Modulus (17 % 3 = 2)
                  # Then addition (5 + 2 = 7)

                  # Comparison and logical operators
                  result5 = 8 > 4 and 6 < 3
                  # 8 > 4 → True
                  # 6 < 3 → False
                  # True and False → False

                  # Complex expression combining multiple operators
                  result6 = (6 + 2) * 3 - 4 / 2
                  # Parentheses (6 + 2 = 8)
                  # Multiplication (8 * 3 = 24)
                  # Division (4 / 2 = 2)
                  # Subtraction (24 - 2 = 22)

                  # Displaying all results
                  print("Result 1:", result1)
                  print("Result 2:", result2)
                  print("Result 3:", result3)
                  print("Result 4:", result4)
                  print("Result 5:", result5)
                  print("Result 6:", result6)





                                                                                           Operators and Expressions  479
   476   477   478   479   480   481   482   483   484   485   486