It is certainly possible to use and and or to ensure that only one if statement in a chain gets run. But it is annoying, and a single mistake can mess up the whole thing.
So what programmers usually use is elif and else. Here is an example!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |
How old is the human? 42 A human 42.0 years old is usually called 'adult'.
elif is pretty simple. It is just like an if statement, but it checks two things.
elif's condition true?if or elif statement true?(elif is an abbreviation for "else if")
When the previous statement was false and the elif's condition is true, then its code gets run. Basically exactly what we did manually in the previous exercise.
The else statement is even simpler. The else's code gets executed if the previous statement was false.
In this program, the elif on line 10 only runs if age is less than 1 and the if statement from line 7 was false.
The elif on line 12 only gets a shot if the one on line 10 was false.
The elif on line 14 only gets a chance when the elif on line 12 was false.
And so on. The else on line 26 only runs if all the previous conditions were false.
- Add the same
ifstatement here that you did in the previous exercise, but useelifthis time. Was it easier? Answer in a comment.
©2017 Graham Mitchell