Complex Conditions
The previous problem can be solved in a shorter way using complex conditions.
Let's understand what
complex conditions are.
The simplest conditions consist of one relation (greater than, less than, etc.). But sometimes it is necessary to combine simple conditions into more complex ones. For example, it is cold outside and it is raining. Two simple conditions (it's cold outside), (it's raining outside) are connected here by the copula I.
COMPLEX CONDITION - consists of two or more simple relations (conditions) that are combined using logical operations :
AND - logical multiplication - written in Python as and
,
< br />
OR - logical addition - written in Python as or
,
NOT - logical negation - in Python written as not
.
Operation
AND - requires simultaneous fulfillment of two conditions:
condition 1 and condition 2 - will evaluate to true only if both simple conditions are true at the same time,
moreover, if condition 1 is false, then condition 2 will not be checked
The operation
OR - requires at least one of the conditions
condition 1 or condition 2 - will evaluate to false only if both simple conditions are false at the same time,
moreover, if condition 1 is true, then condition 2 will not be checked
Operation
NOT
not condition 1 - will evaluate to false if condition 1 is true and vice versa
For example, the following two conditions are equivalent: A>B
and not (A<=B)
Priority of execution of logical operations and relations
- Operations in brackets
- NOT operation
- Logical relationships >, <, >=, <=, ==, !=
- And operation
- OR operation
Parentheses are used to change the order of actions.
Boolean variables
In many programming languages, it is possible to use variables that store boolean values ("true"/"false"). In Python, such variables can take the values
True
(true) or
False
(false). For example, the program
a=True
b=False
print(a or b)
Displays
True
.
Boolean variables are of type
bool
, named after the English mathematician
George Boole, the creator of the algebra of logic.