Course Content

Introduction to Python

## Combining Conditions

In Boolean logic, two fundamental operators are OR and AND. What do they represent? The OR operator checks if either of the conditions is true and returns `True` if so; otherwise, it returns `False`. The AND operator ensures both conditions are true before returning `True`. If not, it returns `False`. In Python, to combine conditions, use the `and` & `or` operators (always in lowercase). For example:

• `condition1 and condition2` yields `True` only when both conditions are `True`.
• `condition1 or condition2` gives `True` if at least one condition is `True`.

Note

You can also chain more than two conditions using these operators. Employ parentheses to clarify the order of operations.

As an illustration, consider these conditions:

1. Whether `2` exceeds `1` and if `"bbb"` isn't the same as `"aaa"`.
2. If the character with index `2` in the string `"my string"` is either `"y"` or `"s"`.
Code Description
In the first line of the code, `2 > 1 and "bbb" != "aaa"` involves two conditions connected by the `and` operator. The first condition `2 > 1` is true because 2 is greater than 1. The second condition `"bbb" != "aaa"` is also true because the strings "bbb" and "aaa" are not equal. Since both conditions are true and they are connected by `and`, the entire expression evaluates to true.

In the second line, `"my string"[2] == "y" or "my string"[2] == "s"` checks two conditions connected by the `or` operator. The expression `"my string"[2]` refers to the third character of the string "my string", which is " ". The first condition `"my string"[2] == "y"` is false. The second condition `"my string"[2] == "s"` is false, and since both of the conditions is false and they are connected by `or`, the overall expression evaluates to false.

How should we interpret the outcomes? The initial `print()` issues a `True` response since both `2 > 1` and `"bbb" != "aaa"` hold true. The following `print()` yields `False` because the character at index `2` is neither `'y'` nor `'s'` (it's actually a space).

Note

If you wish to reverse a boolean value, employ the `not` operator. For instance, `not 1 == 1` results in `False` because `1 == 1` is `True`, and we've negated that to `False`.

#### What output does the subsequent code produce?

`print(0 > 10 and 5 > 2)`: This prints `False` because, while `5 > 2` is true, `0 > 10` is false. The `and` operator requires both conditions to be true, but since one is false, the overall expression is false.
`print(2*2 == 5 or 1+1 != 3)`: This prints `True` because `2*2 == 5` is false, but `1+1 != 3` is true. The `or` operator only requires one of the conditions to be true for the overall expression to be true.