Further investigate the Python programming language by learning about conditions.
Let’s imagine we are developing software for a restaurant, where a tip of 10% is added to the bill. Here’s the code, a simple sequence of assignments and output. For example, the assignment on line 3 states ‘let the tip be the expenses multiplied by the percentage’. Note that in Python the multiplication operator is the asterisk.
Let’s further assume the tip is only automatically added for groups above 6 people. We need one more variable, to store the number of people in the group, and one new instruction to handle both cases: if the number of people is more than 6, the percentage is 10%, otherwise it’s 0%.
Before I explain the code, let’s test it, to make sure it works as intended. Large software companies employ many testers to check their code. Good testing includes choosing enough inputs (preferably borderline cases) to exercise all possible conditions. In this case, we should at least test for 6 and 7 people, the borderlines where the tip percentage changes.
Change the number of people to 6 and confirm the bill is just the expenses in that case.
The selection instruction ‘if condition: block else: block’ chooses which block to execute as follows. The computer checks the condition after the if. If it is true, the computer then executes the block of code (the indented instructions) belonging to the if part. If the condition is false, the computer executes instead the else block. The indentation is needed to know which instructions belong to which part. Afterwards the computer continues executing the non-indented instructions.
Notice there is a colon (:) at the end of the if and else lines. Forgetting the colons and forgetting to indent the instructions will lead to error messages.