@@ -79,9 +79,63 @@ You can attach **only one** else block to **if statement**. And you cannot use
79
79
``elif`` block(s)
80
80
-----------------
81
81
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``.
83
115
84
116
Usage
85
117
-----
86
118
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