How to use logical operators (and, or, not) in Python conditional statements?

Using Logical Operators in Python Conditional Statements

Logical operators in Python are used to combine or modify boolean expressions in conditional statements. The three main logical operators in Python are and, or, and not. These operators allow you to create more complex and precise conditional statements to control the flow of your program.

The and Operator

The and operator returns True if both the operands on either side of the and are True. If one or both of the operands are False, the expression evaluates to False. For example:

x = 5
y = 10
if x > 0 and y > 0:
    print("Both x and y are positive.")
else:
    print("Either x or y is not positive.")

In this example, the conditional statement x > 0 and y > 0 will only evaluate to True if both x is greater than 0 and y is greater than 0.

graph LR A[x > 0] --> B{and} B --> C[y > 0] B --> D[True] B --> E[False]

The or Operator

The or operator returns True if at least one of the operands on either side of the or is True. If both operands are False, the expression evaluates to False. For example:

x = -5
y = 10
if x > 0 or y > 0:
    print("At least one of x or y is positive.")
else:
    print("Both x and y are negative.")

In this example, the conditional statement x > 0 or y > 0 will evaluate to True if either x is greater than 0 or y is greater than 0.

graph LR A[x > 0] --> B{or} B --> C[y > 0] B --> D[True] B --> E[False]

The not Operator

The not operator is a unary operator that negates the boolean value of its operand. If the operand is True, not returns False, and if the operand is False, not returns True. For example:

x = 5
if not x < 0:
    print("x is not negative.")
else:
    print("x is negative.")

In this example, the conditional statement not x < 0 will evaluate to True because x is not negative.

graph LR A[x < 0] --> B{not} B --> C[True] B --> D[False]

By combining these logical operators, you can create more complex conditional statements to control the flow of your Python program. For instance, you can use the and operator to check if two conditions are true, the or operator to check if at least one of the conditions is true, and the not operator to negate a condition.

Remember, the order of operations for logical operators in Python follows the standard PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction) rule, with not having the highest precedence, followed by and, and then or.

0 Comments

no data
Be the first to share your comment!