Skip to content
Skip to main content

About this free course

Author

Download this course

Share this free course

Simple coding
Simple coding

Start this free course now. Just create an account and sign in. Enrol and complete the course for a free statement of participation or digital badge if available.

3.1 And now for something not completely different

Usually there are many ways to solve the same problem. For the problem of adding the 10% tip only to groups over 6 people, we have set the tip rate to 0% or 10% or the tip itself but we can instead change how the tip is calculated.

Activity 4

Keep the rate at 10% but change the way the tip is computed: if there are more than 6 people, let the tip be the expenses times the rate, otherwise let the tip be zero. Change the code accordingly and check your solution against mine  [Tip: hold Ctrl and click a link to open it in a new tab. (Hide tip)] .

Finally, let’s assume the restaurant decides to impose a higher tip of 15% for groups of at least 15 people. In Python we can chain various conditions as follows:

Interactive feature not available in single page view (see it in standard view).

In plain English: if the number of people is larger or equal (>=) to 15, let the percentage be 15%, otherwise if (elifnot else if) it is larger than 6 let the percentage be 10%, otherwise let the percentage be 0%.

Activity 5

Test the code with the four borderline cases: 6, 7, 14 and 15 people.

Note that the order in which we write the conditions is important, because the computer checks them from top to bottom and executes only one block, for the first condition that is true. The else block has no condition, so it’s a ‘catch all’ in case no condition is true.

Activity 6

Explain why the following code is wrong. Hint: repeat the tests and see what happens. That’s what tests are for.

Interactive feature not available in single page view (see it in standard view).