Conditional statement (if)
In the problem of finding the maximum number of two, we met a new operator that began with the word
if.
This operator is called
CONDITIONAL operator.
The word
if
is translated from English as "if", and the word
else
- as "otherwise". If the condition after the word
if
is true (true), then all commands (operators) after the colon on a new line and located before the word
else
are executed. If the condition is false (false), then the commands after the word
else:
.
are executed
Unlike other programming languages,
indentation (shifts) statements relative to the left border are important in Python.
Indentation affects program performance. If you look closely, the word
if and the word
else
start at the same level, and the commands that are executed are shifted to the right relative to this level the same distance (
recommended to use 4 spaces).
GENERAL VIEW OF THE CONDITIONAL STATEMENT:
if condition: # title with condition
# "if" block — statements that are executed
# if the condition in the header is true
else:
# block "otherwise" — statements that are executed
# if the condition in the header is false
You have to remember!
1.
if-else
-
is one statement!
2. After the word
else
, the condition is never set (the condition is set only after the word
if
).
Block "
otherwise" is executed when the main condition specified after the word
if
is false, i.e. not executed.
3. The statements to be executed in each branch (
if
or
else
) are written with the same indentation of 4 spaces.
Indentation required!
4.
Condition is an expression that can be said to be true (i.e., met) or false (i.e., not met).
The condition uses signs of logical relations
>
,
<
more, less,
>=
,
<=
greater than or equal, less than or equal,
==
equals,
!=
not equal.