Alterna · учебный материал

Logical expressions

35.2 Logical expressions: Short theory, one example, and a python stroll.

Что в этом материале

Содержание и основные понятия

And requires the truth of all parts, or — at least one, not changes the result to the opposite. Comparisons can be combined in chains.
substance and practice
Grade 8
OGE No. 6
OGE No. 16
01
How it works.
A difficult condition collects a few simple checks. The brackets, boundaries and short calculations make this code readable and safe.
and.
The truth when both parts are true, the false first part stops calculating the second part.
or.
The truth, when the truth is at least one part; and the true part of the first part stops counting the second part.
not.
Changes True to False and vice versa.
The chain.
Recording 10 <= x <=99 means two related checks, not a comparison of the booleum with the number.
02
One example in execution
Start the short program and go over the lines. The visualiser only shows the code, current line, variables and output.
A short calculation helps protect a dangerous action:
x != 0 and total / x > 2
But don't rely on it secretly: the condition should be read as a matter of course.
and
and
or
They return the operand to the Python-context in general, but we're interested in its logic.
Algorithm map
Read from left to right, then run the code.
1
Start
2
Read Value
3
Compute logical expression
4
Select branch
5
Make the result
03
Remember
Write x = 1 or x = 2 rather than x =1 or 2.
The brackets are mandatory if the mix and or change the meaning of the rule.
Check the case where the first part is false: the dangerous second part must not be fulfilled.
Syntax of this page
and
Logical E; the right part is only fulfilled if the left is true.
or
Logical IL; the right part is only fulfilled if the left is false.
not
Logical denial.
10 <= x <= 99
A chain comparison equivalent to 10 <=x and x <=99 without double calculation of x.
%
Checks the split: x%2 = 0 for an even number.
bool expression
Any comparison can be saved in the variable and used later.
print
Prints True or False or the result of the selected branch.

Structural map of textbooks