Lab# 15 and 16 If Else
Lab# 15 and 16 If Else
Indentation
✓ Python relies on indentation (whitespace at the beginning of a line) to define the scope of the
code.
✓ Other programming languages often use curly brackets for this purpose.
Elif
The elif keyword is Python's way of saying "if the previous conditions were not true, then try this
condition".
✓ In this example a is equal to b, so the first condition is not true, but the elif condition is true,
so we print to screen that "a and b are equal".
Else
✓ The else keyword catches anything that isn't caught by the preceding conditions.
✓ In this example a is greater than b, so the first condition is not true, also the elif condition is
not true, so we go to the else condition and print to a screen that "a is greater than b".
✓ If you have only one statement to execute, you can put it on the same line as the if statement.
✓ If you have only one statement to execute, one for if, and one for else, you can put it all on
the same line:
✓ You can also have multiple else statements on the same line:
And
✓ The and keyword is a logical operator and is used to combine conditional statements.
Or
✓ The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:
Nested If
You can have if statements inside if statements, this is called nested if statements.
if statements cannot be empty, but if you for some reason have an if statement with no content, put
in the pass statement to avoid getting an error.