Custom Search

PYTHON: If...Elif...Else.... Example

Let's set up a program to calculate a bill at a restaurant.

An automatic service charge has to be added for large parties (as they need a lot of attention!)

Parties of 4 or fewer attract no automatic service charge.

But if there are up to 8 people an automatic 5% is added to the bill.

If the number of people is larger (up to 12 diners) a percentage charge of 10% is added

Even larger parties attract a 15% service charge

Naming the variables

We need to choose names for the variables - in the olden days (Basic days!) we would just choose a single letter - but for clarity you can name the variable with a word that 'means something' to you.

For example - we can use 'food' for the food bill total.

If you want to be more specific you can use a double word like 'serviceCharge' - adding the capital lettter to make it easier to read....

We also need to know how many diners there are.

 

food=100
serviceCharge=0
diners=4

 

The conditions

Setting up the conditions has to be done thoughtfully.

 

if diners<=4:

serviceCharge=0

elif diners<=8:

serviceCharge=5

elif diners<=12:

serviceCharge=10

else:

serviceCharge=15

 

We have to order the code in such a way that if the first condition is not met it will go to the second one, then third until all conditions have been excluded before the 'else' condition is implemented. It has to be logical.

You should always test your code. If it passes the syntax checker, then test it with a range of input values (including zero!) to check you get the results you expect.

We can also start from the other end:

if diners>12:

serviceCharge=15

elif diners>=9:

serviceCharge=10

elif diners>=5:

serviceCharge=5

else:

serviceCharge=0

This also gives the results we need...

There is no 'right way' - but it needs to be logical and robust.

Output

This is an important part of the design. If you have a good program but it is not easy to access the output for a user it will not be appreciated.

The output needs to show enough detail to be useful to a user and easy on the eye.

Tweaking with the strings will allow information to be displayed in a way that is easy to read. A blank line can be added, or a line of dashes. It is limited only by your immagination. But get used to thinking about the final 'look' of your output.

Later we will have colour, images and fonts to play with....

But for now...

Just remember to print out everything the user of the program would want to see.

 

print("Food cost = £"),food

print("Number of diners at the table = "),diners

print("Service charge rate = "),serviceCharge,("%")

print("Food cost = £"),food

print("Service charge £"),serviceCharge*food/100

print("Bill Total = £"),food+(serviceCharge*food/100)