Skip to main content

About this free course

Author

Become an OU student

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 this problem, we can either vary the tip rate (as above) or the tip itself (as follows)

Activity 5

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 6

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 7

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).