Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 126 - 2612_Digimind
P. 126

    LOGICAL OPERATORS

                      Logical operators are used  to  combine  conditional  statements  and  return a  Boolean
                      value (True or False) based on the conditions provided. Python supports the following logical
                      operators:

                                                                                          Example
                         Operator         Name                 Description              (x = 5, y = 3)       Output

                                                        Reverses the result, returns
                            not        not              True if the condition is False     not(x > y)          False
                                                        or vice versa.

                                                        Returns True if both
                            and        and                                              x > 3 and y < 4        True
                                                        conditions are True.

                                                        Returns True if at least one
                             or        or                                                x > 3 or y > 4        True
                                                        condition is True.

                      To demonstrate the use of all the logical operators.

                          Program5.py
                       File  Edit  Format   Run    Options   Window    Help

                       # Assign values to variables
                       x = 5
                       y = 3

                       # Logical NOT (not)
                       print("not (x > y):", not (x > y))

                       # Logical AND (and)
                       print("x > 3 and y < 4:", x > 3 and y < 4)
                       # Logical OR (or)
                       print("x > 3 or y > 4:", x > 3 or y > 4)

                          Output

                       not (x > y): False
                       x > 3 and y < 4: True
                       x > 3 or y > 4: True

                      124   Premium Edition-VII

| 121 122 123 124 125 126 127 128 129 130 131 |