5 - Conditional Statements
A key programming concept that will covered today is the use of conditional statements. They allow your code to have multiple execution paths, and exhibit different behavior depending on the conditions of the program. The paths that your code flows down can also be called branches. It is a best practice to keep the number of branches your code can travel down to a minimum. This makes your code cleaner as well as lowers the amount of code your write.
If statements are the main conditional statement that you will use. A single statement will evaluate code and either run the code inside if the condition is met, or skip the enclosed code if the condition is not met. As you can see below, the first conditional if statement is executed, but not the second one.
If you want to execute alternative code if your if condition is not met, you can add an additional else statement. Else statements can be useful for covering conditions that you might not be able to think of at the time. For instance, you may create a number calculator which uses if statements to check user input. If your user manages to enter a letter instead of a number, you could have an else statement which prints "unknown operation performed". This would also cover symbols too.
Sometimes you will have more than one condition that you need to check. One way to do this is with elif. Elif allows you to check for multiple conditions. You can also still add an else branch to cover conditions that don't match any of your other conditions. In the example below, you'll notice that there are two cases where w is equal to either x or y. There are no conditional branches which cover that condition. Therefore, they both fall under the else branch.