Skipping Elif
If the 'if' test condition is True, then any 'elif' and 'else' blocks that follow will all be skipped.
Current Line | 1 | Current Tab | 0 | Time | 0 |
In this example, the "if" condition is True, so LW Python executes the "if" block. The "elif" and "else" blocks will be skipped because the test conditions was True.
Note that an "if" block can be followed by many "elif" blocks as we want. But there can only be 1 "else" block at the end. In other words, we cannot follow an "else" block with another "else" block.
Example of valid code:
a = 4 if a == 0: b = 5 elif a == 1: b = 6 elif a == 2: b = 7 elif a == 3: b = 8 else: b = 9
Invalid example 1:
a = 3 if a == 0: b = 5 else: b = 6 else: b = 7
Invalid example 2:
a = 7 if a == 0: b = 5 elif a == 1: b = 6 else: b = 7 else: b = 8
Invalid example 3:
a = 5 b = 0 elif a == 1: b = 6 else: b = 7
Invalid example 4:
b = 0 else: b = 7
What happens here?
a = 0 b = 0 if a ==0: c = 4 if b == 0: d = 8
The two "if" statements do not affect each other. The first "if" statement runs. Since a == 0 is True, c is set to 4. Now the first "if" statement is finished, and the second "if" statement runs. Since b == 0, d is set to 8.
Please choose all valid Python code.
Comments
Please log in to add comments