Two Galway taxi trips use the same fare rule. Can you write the rule just once?
Can you price two Galway taxi trips without writing the same calculation twice? Suppose the taxi charges four euro to start and two euro per kilometre. The trips are different lengths, but the rule for working out the price stays the same.
On the first line, multiply two by three, then add four. The code stores ten as the short fare. On the second line, multiply two by seven, then add four to get eighteen. You repeat the same calculation, changing only the distance.
Watch three kilometres go in. The rule doubles the distance and adds four. Ten euro comes back. You can give this reusable calculation the name fare. It becomes a function you can call by name whenever you need a price.
The same fare rule applies to a trip of five kilometres. You still start at four euro and add two euro for each kilometre. What value does the function send back this time? Pick an answer.
Start with pseudocode, a way to plan the algorithm without using Python syntax. The function is called fare. Its parameter, k m, holds the distance supplied for a trip. Double that distance, add four and return the result to the code that called the function.
In Python, def starts the definition of fare with the parameter k m. The indented return line calculates and sends back the fare. Below the definition, the first call passes three and stores the result. The next passes seven and stores its result. The last line adds the two fares.
On the first call, k m takes the value three. Four plus two times three gives ten, which the caller saves as short fare. On the second call, k m takes seven. The function returns eighteen, so the caller saves that as long fare and adds both fares to get twenty-eight.
Now the calling code adds the result of fare of two to the result of fare of five. Work out what each call returns before you add them. What total does the calling code get? Pick an answer.
With return, fare of three gives the caller ten, ready to store or add. If you replace return with print, you might think the caller still gets ten because it appears on screen. Trace the call to the end: Python returns None, so the caller has no fare to add.