You’re a member on a peak-time train. Could one line of code give you the wrong fare?
Say a Galway train offers a discount to members or children, but only off peak. You’re a member and you board at peak time. Would the booking code give you the discount? A pair of parentheses can change the answer.
You’ve used an if statement to make a decision. Take age less than sixteen as the comparison for this example. For a passenger aged fifteen, it gives True. You can store that result as child and use it in an if statement.
The first passenger passes the passenger test by being a member. The second passes by being a child. The third is both and still passes. The last is neither, so the test gives false. In Python, you join those two flags with or.
A passenger is both a member and a child. For now, leave the travel time out of it. What does member or child give you? Pick an answer.
List the four member and child combinations. Off peak, not peak is true. And requires the passenger test and the time test to pass, so only the first row fails in this column. At peak time, not peak is false, so all four discounts are false. The two result columns cover eight cases.
Give the function the three Boolean inputs. If the passenger is a member or a child, and the journey is off peak, return true. Otherwise, return false. This is selection: the condition decides which result the function returns.
Take a child who isn’t a member and travels off peak. Group the passenger test in parentheses. Substitute false, true and false for the three flags. Inside the parentheses, false or true gives true. Then not false gives true. Finally, true and true gives true, so the passenger gets the discount.
Back to your Galway train. You’re a member, you aren’t a child and it’s peak time. Use the grouped condition from the example. Does the booking code give you the discount? Pick the result and its reason.
Read the first expression without parentheses. Python gives not higher priority than and, and gives and higher priority than or. So the time check only affects the child test, and a peak-time member qualifies. Now group member or child. The time check applies to everyone, so a peak-time member gets no discount.
An exam question might ask you to write a function that returns whether a passenger qualifies. Return the grouped condition. Then loop through two tests for a member who isn’t a child. Expect true off peak and false at peak time. Compare each result with its expected value. Both comparisons should print true.