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

Take your learning further

Making the decision to study can be a big step, which is why you'll want a trusted University. The Open University has 50 years’ experience delivering flexible learning and 170,000 students are studying with us right now. Take a look at all Open University courses.

If you are new to University-level study, we offer two introductory routes to our qualifications. You could either choose to start with an Access module, or a module which allows you to count your previous learning towards an Open University qualification. Read our guide on Where to take your learning next for more information.

Not ready for formal University study? Then browse over 1000 free courses on OpenLearn and sign up to our newsletter to hear about new free courses as they are released.

Every year, thousands of students decide to study with The Open University. With over 120 qualifications, we’ve got the right course for you.

Request an Open University prospectus371