Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Operators and Expressions

Use logical and, or, not to combine conditions - Python Program

# Variables for demonstration age = 25 is_student = True has_discount = False item_price = 120 # --- Logical AND (and) --- # Returns True if BOTH conditions are True print("--- Logical AND (and) ---") if age >= 18 and is_student: print("Condition 1: Eligible for student benefits.") else: print("Condition 1: Not eligible for student benefits.") # --- Logical OR (or) --- # Returns True if AT LEAST ONE condition is True print("\n--- Logical OR (or) ---") if is_student or has_discount: print("Condition 2: Eligible for a special offer.") else: print("Condition 2: Not eligible for a special offer.") # --- Logical NOT (not) --- # Reverses the boolean value of a condition print("\n--- Logical NOT (not) ---") if not has_discount: print("Condition 3: No discount applied.") else: print("Condition 3: Discount already applied.") # --- Combining operators --- print("\n--- Combining Operators ---") # Example: Free shipping if total price is over 100 AND either a student OR has a discount if item_price > 100 and (is_student or has_discount): print("Condition 4: Eligible for free shipping.") else: print("Condition 4: Not eligible for free shipping.")

Output

 
OUTPUT  :
--- Logical AND (and) ---
Condition 1: Eligible for student benefits.

--- Logical OR (or) ---
Condition 2: Eligible for a special offer.

--- Logical NOT (not) ---
Condition 3: No discount applied.

--- Combining Operators ---
Condition 4: Eligible for free shipping. 

Explanation

  • andoperator:

This operator evaluates to True only if both operands (conditions) on its left and right are True. If even one operand is False, the entire expression becomes False. In "Condition 1," age >= 18 is True and is_student is True, so the and condition is met.

  • oroperator:

This operator evaluates to True if at least one of its operands (conditions) is True. It only becomes False if both operands are False. In "Condition 2," is_student is True, so the or condition is met even though has_discount is False. 

  • notoperator:

This is a unary operator that inverts the boolean value of its operand. If the operand is True, not makes it False, and vice-versa. In "Condition 3," has_discount is False, so not has_discount evaluates to True. 

  • Combining operators:

Parentheses can be used to control the order of evaluation in complex expressions, similar to mathematical operations. In "Condition 4," the or condition (is_student or has_discount) is evaluated first, and its result is then combined with item_price > 100 using the and operator. This demonstrates how multiple logical operators can be chained together for intricate conditional checks.