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

Condition if / elif / else

35.1: Condition if / elif / else. Short theory, one example and Python stepway.

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

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

The if/elif/else chain is seen from the top down and performs only the first branch with the true condition.
substance and practice
Grade 8
OGE No. 6
OGE No. 16
01
How it works.
The branch does not follow all the appropriate lines: the chain if/elif/else selects the first true check and skips the rest of the chain.
Condition.
The expression after if is calculated in True or False.
Retreat.
Four gaps form a block that belongs to the branch.
elif.
Only checked if the previous conditions of the chain are false.
else.
Covers all remaining cases and does not contain its own conditions.
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.
Checks from a more special case to a more general one. For example, zero cannot be found after the branch.
x >= 0
, because it's already going to take over that value.
==
not.
=
: One label assigns value and is not a comparison.
Algorithm map
Read from left to right, then run the code.
1
Start
2
Read x
3
x > 0?
4
Yes: plus · No: check x = 0
5
Answer
03
Remember
Check the dots to the border, at the border and beyond.
Do not mix independent if with one elif chain: these are different routes.
SyntaxError often refers to a missed colon or incorrect retreat.
Syntax of this page
if condition:
The branch starts; after the condition, the symbol : and the exit block is mandatory.
elif condition:
A further check on the same chain.
else:
It happens if all the terms of the chain are false.
== и !=
A comparison of equality and inequality.
< <= > >=
Comparisons of order; <= and >= include boundary.
bool
Type of logical result: True or False.
int(input())
Reads the number on which the route is chosen.
print
The selected label or result shall be removed.

Structural map of textbooks