…
…
Python Programming Fundamentals · Lesson 6 / 40 · Conditions
PreviewIn this lesson you will
in, and, or, and notifYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
At Corner Café, members who spend $5 or more get a free cookie. Ada works this rule out in her head on every order, and during the rush she sometimes forgets. In this lesson you will teach the rule to a program and let the program make the decision.
So far, every program you wrote ran all of its lines from top to bottom, every time. Real programs make decisions all the time: Is the total high enough? Is the customer a member? Does the order contain a cookie? Depending on the answer, a line either runs or is skipped. In this lesson you will first learn to ask Python a question, then to combine questions, and finally to run a line depending on the answer.
At the end of the lesson, the program you write will print this for a member who spends $6:
OutputFree cookie
Order receivedFor a $4 order it will print only Order received. The same program looks at the values and decides for itself which lines to run.
To make a decision, you first have to ask a question. In Python, comparison operators ask the questions. A comparison works like a calculation, but its result is not a number, it is an answer: either True or False. The type of these two values is bool. Because the answer is a value, you can print it or store it in a variable.
| Operator | Question it asks | Example | Result |
|---|---|---|---|
== | Equal? | 85 == 85 | True |
!= | Different? | 85 != 40 | True |
< | Less than? | 40 < 25 | False |
> | Greater than? | 85 > 40 | True |
<= | Less than or equal? |
There is also `in`: it asks whether the string on the left appears inside the string on the right. The question "Does the order contain a cookie?" becomes "cookie" in order. In Python you can chain two comparisons the way you do in math: 8 <= hour < 12 asks "is the hour between 8 and 12, including 8 but not 12?"
Example 1 (case): The café's questions. The code below asks five questions. Look closely at the last two lines: the answer is first put into the big_order box, and then printed.
total = 6 print(total >= 5) print(total == 5) hour = 15 print(8 <= hour < 12) order = "2 lattes, 1 cookie" print("cookie" in order) big_order = total >= 5 print(big_order) print(type(big_order))
OutputTrue
False
False
True
True
<class 'bool'>On the line total >= 5, the right side is calculated first: is 6 greater than or equal to 5? Yes, so the result is True. Then this True is put into the big_order box. Asking a question once and keeping the answer under a meaningful name makes long rules much easier to read.
The total is exactly $5. What does this code print?
total = 5
print(total > 5)This prediction tests the point that people mix up most often when they turn rules into code: the boundary value. "5 or more" and "more than 5" sound very close in English, but they give different results for an order of exactly $5. Words like "or more", "at least", and "inclusive" need >=; words like "more than", "over", and "exceeds" need >. Before you write a rule, ask yourself: "What should the value right on the boundary get?"
The two operators people confuse most in comparisons are = and ==. The single = you saw in lesson 2 does assignment: it puts the value on the right into the box on the left, and asks nothing. The double == asks about equality, and its answer is True or False.
When you compare strings, the letters must match exactly. Remember lesson 4: "Latte" and "latte" are different strings, so "Latte" == "latte" is False. in is also case-sensitive: "dictionary" in "Pocket Dictionary" is False, because the string contains Dictionary with a capital D. If you compare a number with a string using < or >, you get a TypeError, just as in lesson 4: the line 10 < "5" gives TypeError: '<' not supported between instances of 'int' and 'str'.
Now try turning English rules into expressions. For each rule on the left, choose the right expression. Two extra options were added, and neither fits any rule.
Match each rule with the Python expression that asks it.
For each row, pick its match from the list, then check.
One last warning: in lesson 3 you saw that 0.1 + 0.2 gives 0.30000000000000004. Because floats are stored approximately in a computer, comparing them with == can mislead you. Now that you know ==, predict this one yourself.
What does this code print?
print(0.1 + 0.2 == 0.3)and, or, notThe café's rule is not made of a single question: "$5 or more" is one question, "is a member?" is another. Both have to be met together. There are three logical operators for combining questions. and needs both conditions to be true. or is satisfied when at least one is true. not flips a single answer: it turns True into False and False into True.
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
True | True | True | True | False |
True | False | False | True | False |
False | True | False | True |
You do not need to memorize the table; the meaning is the same as in everyday English. "You can withdraw cash if you have your card and your PIN": if either one is missing, you cannot. "You can pay with cash or by card": one is enough.
Example 2 (case): A student who is not a member. The customer spends $6 and is a student, but not a member.
total = 6 student = True member = False print(total >= 5 and member) print(student or member) print(not member)
OutputFalse
True
TrueOn the first line, total >= 5 is true but member is false; and needs both, so the result is False. On the second line, student is true, and that is enough for or. On the third line, not flips the value of member. Follow the code below step by step and watch what goes into the has_discount box on each line.
Run the code line by line: see which line runs next, the variable boxes and the output.
total = 10 member = False has_discount = total >= 10 or member print(has_discount) print(not member) print(total == 10 and member)
Now change the values yourself. As you change the total and the membership, see how the output of the three lines changes across the four cases. Predict first, then press the button.
What do and, or, and not say when the total and membership change?
Pick a value; predict the output first, then look.
1total = 62member = True3print(total >= 5 and member)4print(total >= 5 or member)5print(not member)
True True False
Faded lines didn't run with this value. The and line is True only for 6 with a member. The or line is False only for 4 with a non-member. The not line never looks at the total; it only flips the membership.
When you turn the café's rules into code, first write the rule out clearly in English. The words "and", "or", and "not" in the sentence almost always tell you which operator to use. "Students or members get a discount" becomes student or member. "A member who spends $5 or more gets a gift" becomes total >= 5 and member. "If the café is not closed" becomes not closed. There is one small trap here: the "or" in "$5 or more" is not a logical connector, it describes the boundary; it means >=. The connector "and" is the one that joins two separate questions.
When an expression has several logical operators, Python calculates the comparisons first, then not, then and, and or last. Whenever you are unsure, use parentheses: for example, not (student or member). We will come back to the details of precedence in lesson 8.
ifNow you can ask the right question. But so far you have only printed the answer on the screen. That is not what Ada wants: when the rule is met, she wants the program to do something. This is what if is for. Its syntax has three parts: the word if, a condition, and a colon (:) at the end of the line. The lines under it start 4 spaces in; these indented lines are called a block. If the condition is True, the block runs; if it is False, Python skips the block. The first line without indentation no longer belongs to the if, and it runs whatever the condition is.
Example 3 (case): The gift rule. The target program of the lesson.
total = 6 member = True if total >= 5 and member: print("Free cookie") print("Order received")
OutputFree cookie
Order receivedOn line 3, Python evaluates the condition: 6 >= 5 is true, member is true, and with and the result is True. So the indented line 4 runs. Line 5 has no indentation, so it is outside the if; it runs on every order. Change the total and the membership below: the lines that run are highlighted, and a skipped print stays faded. Notice that Order received is printed in all six cases.
Which orders get a gift? Look at the lines that run.
Pick a value; predict the output first, then look.
1total = 62member = True3if total >= 5 and member:4 print("Free cookie")5print("Order received")
Free cookie Order received
Faded lines didn't run with this value. The gift line runs only when both conditions are true together: the total is 5 or 6 and the customer is a member. Exactly 5 also gets a gift, because the rule is written with >=. The last line has no indentation and is not tied to the if, so it runs in all six cases.
The most important idea in this section is this: the lines that come after if are not all tied to the condition. Python knows which lines belong to the block only from the indentation. If you want a line to depend on the condition, indent it; if you want it to run every time, write it without indentation.
Now it is your turn. The target program is ready in the cell below. After each change, press Run and explain to yourself why the output changed. (1) Write or instead of and and set member = False: who gets a gift now? (2) Indent the second print with 4 spaces too, and try total = 4, member = False: what changed? (3) Change the rule so that the gift goes to a customer who is NOT a member and spends more than $10.
Try it now· not graded; doesn't affect progress
In this lesson, if has only one path: if the condition is true, do something; if not, do nothing. Doing something else when the condition is false, and choosing among more than two options, is the subject of the next lesson.
ifThe = and == mix-up shows up right away on an if line. Imagine you want to catch an order of exactly $5 and you write this:
total = 5 if total = 5: print("Exactly 5")
Python does not run this program at all, and it points to the place of the error:
Output File "<kod>", line 2
if total = 5:
^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?As you learned in lesson 5, read the message from the bottom: SyntaxError says Python could not understand the line. The suggestion at the end gives the fix too: here you do not want to put something, you want to ask, so you need ==. The correct line is if total == 5:. (:= is a different tool; we will not use it in this course.)
Finally, build a program by putting the lines in the right order. The program should first take the total, keep the answer to "is it a big order?" in a variable, print a gift line for a big order, and say Enjoy your meal to every customer at the end. Pay attention to the indentation.
Order the lines: a gift for a big order, and "Enjoy your meal" for everyone at the end.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The same structure is useful outside the café too. A library has two rules: a book that is more than 14 days late gets a fine; books with Dictionary in the title cannot be borrowed. The two ifs are independent of each other: Python asks about both separately.
days_late = 16 book = "Pocket Dictionary" if days_late > 14: print("Late fine") if "Dictionary" in book: print("Cannot be borrowed") print("Done")
OutputLate fine
Cannot be borrowed
DoneIn Example 4, if the first line becomes days_late = 14, how many lines does the program print?
days_late = 14 book = "Pocket Dictionary" if days_late > 14: print("Late fine") if "Dictionary" in book: print("Cannot be borrowed") print("Done")
Ada is starting a new promotion: "On weekdays, for students who arrive between 8 and 11 in the morning (11 excluded), tea costs $0.75." Instead of writing a long rule in one go, split it into steps. The comment lines name the steps; you can use the same steps in the exercises.
# 1. Get the information hour = 9 student = True weekend = False tea = 1.25 promo = 8 <= hour < 11 student weekend promo: tea = 0.75 (, promo) ( + (tea))
Leaving a comparison half finished with `or`. Writing the question "Is the item a latte or tea?" like an English sentence feels very natural, but Python does not read it the way you mean it:
item = "water" print(item == "latte" or "tea") print(item == "latte" or item == "tea")
Outputtea
FalseOn the first line, Python reads the expression as (item == "latte") or "tea". The left side is False, so or looks at the right side and returns the string "tea". Inside an if, a non-empty string counts as true; so the line if item == "latte" or "tea": runs for water, for cookies, for every item (the details of why come in lesson 8). The right way: write a complete question on both sides of or, as in item == "latte" or item == "tea".
The same incompleteness also has a visible form. If you write only == "tea" after or
==, !=, <, >, <=, >=, and in ask a question and answer with True or False (bool); = puts, == asks; "or more" means >=, "more than" means >.and needs both conditions to be true, or needs at least one, and not flips the answer; the words "and", "or", and "not" in an English rule tell you the operator.if condition: runs only when the condition is True; a line without indentation runs in every case.Next lesson: We will use else
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
5 <= 5True |
>= | Greater than or equal? | 4 >= 5 | False |
TrueFalse | False | False | False | True |
OutputPromo: True
Tea: $0.75The three parts of the rule became three questions: the hour range is a chained comparison, "for students" is student, and "on weekdays" is "not a weekend", that is, not weekend. All three are needed, so and goes between them. This time the if block does not print anything, it changes a value: if the condition is true, 0.75 goes into the tea box; if not, it stays 1.25.
Several rules can apply to one order at the same time. First store the answer to each rule under a meaningful name, then write a separate if for each one.
total = 7 student = True member = True gift = total >= 5 and member discount = student or member if discount: print("Discount applied") if gift: print("Free cookie") print("Total: $" + str(total))
OutputDiscount applied
Free cookie
Total: $7The helper variables (gift, discount) make the if lines read like an English sentence: "if discount", "if gift". If total = 4, only the discount line and the total would be printed; if student and member were both False, only the total.
item = "water" if item == "latte" or == "tea": print("Hot drink")
Output File "<kod>", line 2
if item == "latte" or == "tea":
^^
SyntaxError: invalid syntaxThe arrows are under ==: after or, Python expected a new value or question, but it ran straight into a comparison operator. == compares two things; it cannot stand without something on its left to compare. This is a good error, because it shows you where the problem is. The really dangerous one is the or "tea" form above: it runs wrongly without raising any error. The fix is the same in both cases: on both sides of or, write the variable, the sign, and the value in full.
elif