Skip to content

Commit 27b1354

Browse files
committed
explaining if statements better thanks horusr and Pytholico
1 parent de8dc10 commit 27b1354

File tree

1 file changed

+41
-2
lines changed

1 file changed

+41
-2
lines changed

basics/if.md

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,8 +162,7 @@ a password from the user, but you shouldn't worry about that just yet.
162162

163163
## Avoiding many levels of indentation with elif
164164

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:
167166

168167
```python
169168
print("Hello!")
@@ -187,6 +186,11 @@ else:
187186
print("I don't know what", word, "means.")
188187
```
189188

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+
190194
Instead of typing `else`, indenting more and typing an `if` we can
191195
simply type `elif`, which is short for `else if`. Like this:
192196

@@ -208,6 +212,41 @@ else:
208212
print("I don't know what", word, "means.")
209213
```
210214

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+
211250
## Summary
212251

213252
- If a code example starts with `>>>` run it on the interactive prompt.

0 commit comments

Comments
 (0)