PYTHON: If...Elif...Else.... ExampleLet's set up a program to calculate a bill at a restaurant.
Naming the variablesWe 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
The conditionsSetting up the conditions has to be done thoughtfully.
if diners<=4:
elif diners<=8:
elif diners<=12:
else:
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:
elif diners>=9:
elif diners>=5:
else:
This also gives the results we need... There is no 'right way' - but it needs to be logical and robust. OutputThis 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) |
|