One simple condition is often not enough. A person can enter a club if they are old enough and have a ticket. A shop gives a discount to students or to senior citizens. In this course you combine conditions with and, or and not, check a range, ask whether a value is inside a group with in, and put one decision inside another. You learn to prove a combined condition with a truth table, and to simplify a condition with the rule of not. A club entry program at the end uses everything. The practice tests your conditions on many cases and tells you which ones fail.
5 lessons, about 2 h 30 min5 simulations13 problems10 practice questionsPython in every lesson
and, or and not join conditions. A and B is True only when both are True. A or B is True when at least one is True. not A turns True into False and False into True. In a long condition, Python does not first, then and, then or, and brackets change the order. Write each comparison in full: age >= 18 and age <= 60 is right, and age >= 18 and <= 60 is a SyntaxError.
To check a range, write two comparisons joined by and, or use the short chain 50 <= marks <= 75. The word in asks whether a value is inside a group: a letter in a text, a word in a longer text, or a value in a list. not in is the opposite. A condition such as letter == 'a' or 'e' is a trap, because the text 'e' alone is always True, so each comparison must have its own left side. Use in to write such a test in one short line.
A decision can sit inside another decision. The inner if is asked only when the outer condition is True, and it needs one more level of indent. Nested decisions give different messages for different reasons, but they quickly become hard to read. The same logic can often be written flat with and and elif. Choose the form that is easier to read, test every branch, and avoid going deeper than two levels.
A truth table lists every possible combination of True and False for the parts of a condition and the result for each. With two parts there are four rows, and with three there are eight. A truth table proves that two conditions are the same. The rule of not says that not (A and B) is the same as (not A) or (not B), and not (A or B) is the same as (not A) and (not B). Use it to simplify a condition. A leap year check is a good example, with the rule: divisible by 4, except for a century year that is not divisible by 400.
In this project we write the entry rules of a club. Under 18 is never allowed. At 18 or more, a person needs a ticket, but a member enters without a ticket. We write the rules in plain words, build a table of the cases, write the condition with and, or and not, test all the combinations, and then extend the club with a closing time and a guest rule. The project uses combined conditions, a flat decision with elif, and a test table with every branch.
Log in to join the discussion.
Loading…