Explain the logical operations with examples.
时间: 2024-03-10 15:49:47 浏览: 17
Logical operations are used in computer programming to manipulate Boolean values (true or false). There are three main logical operators: AND, OR, and NOT.
1. AND Operator: The AND operator returns true only if both operands are true. Otherwise, it returns false.
Example:
```
x = 5
y = 3
z = 7
if x > y and x < z:
print("x is between y and z")
else:
print("x is not between y and z")
```
In the above example, the AND operator returns true only if both conditions are true: x is greater than y and x is less than z.
2. OR Operator: The OR operator returns true if either one or both operands are true. It returns false only if both operands are false.
Example:
```
x = 5
y = 3
z = 7
if x > y or x > z:
print("x is greater than either y or z")
else:
print("x is not greater than either y or z")
```
In the above example, the OR operator returns true if either one of the conditions is true: x is greater than y or x is greater than z.
3. NOT Operator: The NOT operator is a unary operator that returns the opposite of the Boolean value of the operand. If the operand is true, it returns false. If the operand is false, it returns true.
Example:
```
x = True
if not x:
print("x is false")
else:
print("x is true")
```
In the above example, the NOT operator returns the opposite of the Boolean value of x. Since x is true, the NOT operator returns false.