Previous Index Next

Logical Operators in Decision Structure

Logical operators in Decision structure are used to combine Boolean expressions. There are three logical operators in Python.

"and" Operator

The "and" operator is used to combine two or more conditions. It returns True if all the conditions are true. Otherwise, it returns False.

Example 1: Checking Age and Salary for Loan Eligibility

age = 25
salary = 50000

if age >= 18 and salary >= 30000:
    print("You are eligible for a loan.")
else:
    print("You are not eligible for a loan.")

Example 2: Checking if a Number is both Positive and Even

num = 8
if num > 0 and num % 2 == 0:
    print("The number is positive and even.")

Example 3: Checking if a User Entered a Valid Username and Password

username = "admin"
password = "pass123"
if username == "admin" and password == "pass123":
    print("Login successful!")

"or" Operator

The "or" operator is used to combine two or more conditions. It returns True if at least one of the conditions is true, and False if all the conditions are false.

Example 1: Checking if a Student has Passed in at Least One Subject

subject1 = 70
subject2 = 55
      
if subject1 >= 50 or subject2 >= 50:
    print("The student has passed in at least one subject.")
else:
    print("The student has failed in all subjects.")

Example 2: Checking if a Number is Either Divisible by 2 or 5

num = 17

if num % 2 == 0 or num % 5 == 0:
    print("The number is divisible by either 2 or 5.")
else:
    print("The number is not divisible by 2 or 5.")

"not" Operator

The "not" operator returns the opposite of condition. It returns True if the condition is false, and False if the condition is true.

Example: Checking if a User is Not Logged In

is_logged_in = False
      
if not is_logged_in:
    print("Please log in to continue.")
else:
    print("Welcome!")

Short-Circuit Evaluation in Python

In Python, a "short circuit" refers to the behavior of logical operators (and and or) when evaluating boolean expressions. It means that the evaluation of the expression stops as soon as the result can be determined without evaluating the remaining part of the expression.

Short-Circuit Evaluation with the "and" Operator

If the expression on the left side of the "and" operator is false, the expression on the right side will not be checked.

x = 5
y = 10

# In this case, the left side of the 'and' operator is False, so the right side is not evaluated.
if x > 10 and y > 5:
    print("This will not be printed")

Short-Circuit Evaluation with the "or" Operator

If the expression on the left side of the "or" operator is true, the expression on the right side will not be checked.

x = 5
y = 10

# In this case, the left side of the 'or' operator is True, so the right side is not evaluated.
if x < 10 or y < 5:
    print("At least one condition is True")

Previous Index Next