Skip to content
This repository was archived by the owner on Jul 2, 2024. It is now read-only.

Commit 9f95352

Browse files
committed
Added usage example for if/elif/else statements
Signed-off-by: Serhii Horodilov <sgorodil@gmail.com>
1 parent 4baedc7 commit 9f95352

File tree

1 file changed

+56
-2
lines changed

1 file changed

+56
-2
lines changed

src/basics/controlflow.txt

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,63 @@ You can attach **only one** else block to **if statement**. And you cannot use
7979
``elif`` block(s)
8080
-----------------
8181

82-
.. todo: provide elif examples
82+
``elif`` (*else if*) statement may be considered as semi-statement between
83+
``if`` and ``else`` statements. In case your program has more than two
84+
dedicated choices you are able to extends control flow by appending
85+
``elif`` blocks after ``if`` statement. The syntax is pretty similar to ``if``
86+
statement. Each ``elif`` has its own boolean expression or an object to test
87+
for the truth value.
88+
89+
You can attach as many ``elif`` statements as it needed. But you cannot use
90+
``elif`` without ``if`` statement.
91+
92+
Python will test conditions in ``if`` and ``elif`` statements from top to
93+
bottom. The first one, which considered to be ``True`` will be executed.
94+
All others will be skipped.
95+
96+
If there were no truth conditions ``else`` block will be executed (if exists).
97+
98+
.. code-block:: python
99+
100+
>>> x = int(input("Enter some integer number: "))
101+
>>> if not x % 5 and not x % 3: # the same as x % 5 == 0 and x % 3 == 0
102+
... print(x, "is divisible by 5 and 3")
103+
... elif not x % 5:
104+
... print(x, "is divisible by 5")
105+
... elif not x % 3:
106+
... print(x, "is divisible by 3")
107+
... else:
108+
... print(x, "is not divisible by 5 or 3")
109+
110+
.. note::
111+
112+
The order conditions appears matter.
113+
The truth test goes from top to bottom and stops at first expression
114+
which is ``True``.
83115

84116
Usage
85117
-----
86118

87-
.. todo: branching the code
119+
``if/elif/else`` statements help you to control which portion of your code is
120+
executed based on conditions from outer scope.
121+
122+
.. code-block:: python
123+
:linenos:
124+
125+
# Ask user for input
126+
grade = int(input("Enter your grade (0-100): "))
127+
128+
# Use if/elif/else statements to assign letter grade
129+
if grade >= 90:
130+
letter_grade = "A"
131+
elif grade >= 80:
132+
letter_grade = "B"
133+
elif grade >= 70:
134+
letter_grade = "C"
135+
elif grade >= 60:
136+
letter_grade = "D"
137+
else:
138+
letter_grade = "F"
139+
140+
# Print the letter grade
141+
print("Your letter grade is:", letter_grade)

0 commit comments

Comments
 (0)