Trace a ticket rule — quick review
Imagine a museum that prints its ticket rule on a board.
A block may hold another if statement. The inner statement's blocks are indented one level further, by four more spaces in this course. Python reaches the inner if only when the block that holds it runs. Each else or elif belongs to the if whose line starts at the same depth.
Write the inputs for one test case at the top of a sheet, with the output you expect from the rule in words.
Go down the program one line at a time. At an assignment, record the new value of the name.
At an
iforelifline, work out the condition with the current values and write True or False beside it.If it is True, move into the block beneath it. If it is False, skip every line indented further than that line and continue at the next line that is indented the same amount or less.
After one block of an
ifstatement has run, skip its remainingelifandelsebranches.Compare the output with what you expected. Repeat with further test cases until every block has run at least once.
Moving a line sideways can change which decision it belongs to, and Python accepts both versions. Suppose the whole if member: statement is moved four spaces to the left, so that its first line starts at the margin. It no longer sits inside the outer else block, so Python reaches the test for every visitor, and every member gets the discount. A member aged 3 then gets 0 - 2, and the program displays Ticket: -2 coins. Trace one case for each branch after you change any indentation.
A second slip is tracing only the case you had in mind when you wrote the code. The case you traced proves nothing about a visitor who takes a different branch. Check the list of test cases against the blocks, and add a case for any block that no test reaches.