Until now, a program did every line, one after the other. In this course it learns to choose. You compare values, run some lines only when a condition is True, choose between two and then between many possibilities, and learn how to test every branch so that the program is right at the edges, where mistakes hide. You finish with a ticket office program. The practice runs your decisions on many test values and tells you which ones fail.
5 lessons, about 2 h 35 min5 simulations13 problems10 practice questionsPython in every lesson
A comparison asks a question about two values and gives True or False. The six signs are ==, !=, <, >, <= and >=. One equals sign stores a value, and two equals signs compare. Text can be compared too: a capital letter makes it different, and text is compared in alphabetical order. The answer of a comparison is a bool value, so we can keep it in a variable.
An if statement runs the lines under it only when its condition is True. The line ends with a colon, and the lines that belong to it are indented by four spaces. An else part runs when the condition is False. Only one of the two parts runs, and the lines with no indent run every time. An if can stand alone with no else. Ask the user with input() and decide with if, and use a remainder with == to test for even and odd.
elif means else if. Python checks the conditions from the top, runs the lines of the first condition that is True and skips all the rest. else at the end catches everything that no condition caught. The order of the checks matters: put the most special condition first, because the first True one wins. A grade by marks and a ticket price by age are typical programs with an elif ladder.
A decision must be tested at every branch, and especially at the edges, where one condition changes into the next, because that is where most mistakes hide. Make a test table: the input, the answer that you expect from the rules, and the answer of the program. Test one value inside each branch and the values on both sides of each edge, such as 49, 50 and 51. The usual bugs are the wrong order, a one-off edge between < and <=, a missing else, and = instead of ==. A dry run, following the program by hand, finds them.
In this project we write a ticket office. The price depends on the age, as in the ticket ladder, and a weekend adds 20 rupees to every ticket that is not free. We write the rules first, then a test table with the edges, then the program in two steps, and we run the tests. We then extend the office with a rule for groups and a discount code, and test again. The project uses comparisons, if, elif, else, and a second decision that comes after the first.
Log in to join the discussion.
Loading…