@@ -162,8 +162,7 @@ a password from the user, but you shouldn't worry about that just yet.
162
162
163
163
## Avoiding many levels of indentation with elif
164
164
165
- If we have more than one condition to check, our code will end up
166
- looking a bit messy.
165
+ If we have more than one condition to check, we could do this:
167
166
168
167
``` python
169
168
print (" Hello!" )
@@ -187,6 +186,11 @@ else:
187
186
print (" I don't know what" , word, " means." )
188
187
```
189
188
189
+ This code is a mess. We need to indent more every time we want to check
190
+ for more words. Here we check for 5 different words, so we have 5 levels
191
+ of indentation. If we would need to check 30 words, the code would
192
+ become really wide and it would be hard to work with.
193
+
190
194
Instead of typing ` else ` , indenting more and typing an ` if ` we can
191
195
simply type ` elif ` , which is short for ` else if ` . Like this:
192
196
@@ -208,6 +212,41 @@ else:
208
212
print (" I don't know what" , word, " means." )
209
213
```
210
214
215
+ Now the program is shorter and much easier to read.
216
+
217
+ Note that the ` elif ` parts only run if nothing before them matches, and
218
+ the ` else ` runs only when none of the ` elifs ` match. If we would have
219
+ used ` if ` instead, all possible values would be always checked and the
220
+ ` else ` part would run always except when word is ` "gday m8" ` . This is
221
+ why we use ` elif ` instead of ` if ` .
222
+
223
+ For example, this program prints only ` hello ` ...
224
+
225
+ ``` python
226
+ if 1 == 1 :
227
+ print (" hello" )
228
+ elif 1 == 2 :
229
+ print (" this is weird" )
230
+ else :
231
+ print (" world" )
232
+ ```
233
+
234
+ ...but this prints ` hello ` * and* ` world ` :
235
+
236
+ ``` python
237
+ if 1 == 1 :
238
+ print (" hello" )
239
+ if 1 == 2 :
240
+ print (" this is weird" )
241
+ else :
242
+ print (" world" )
243
+ ```
244
+
245
+ Now the ` else ` belongs to the ` if 1 == 2 ` part and ** it has nothing to
246
+ do with the ` if 1 == 1 ` part** . On the other hand, the elif version
247
+ chained the multiple ifs together and the ` else ` belonged to all of
248
+ them.
249
+
211
250
## Summary
212
251
213
252
- If a code example starts with ` >>> ` run it on the interactive prompt.
0 commit comments