…
…
Python Programming Fundamentals · Lesson 8 / 40 · Conditions
PreviewIn this lesson you will
if into a single conditionNone using truthinessYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Some orders that come from Corner Café's online order screen are faulty: the item name may be empty, the quantity may be 0, or the coupon field may never have been filled in. Ada wants these orders to be stopped before they reach the kitchen. In this lesson you will write conditions that ask several rules at once and recognize the "no value" case.
At the end of the lesson, the program you write will give this answer to an order that arrives with an empty item name:
OutputNo item selectedIf an item has been selected, the program will look at the quantity; if the quantity is acceptable, it will accept the order, and if the customer entered a coupon, it will print the coupon too. For this you need three new abilities. First, to make Python calculate several conditions in the order you mean. Second, to write step-by-step decisions both correctly and simply. Third, to recognize values that were left empty or never entered.
In this lesson you will:
if, and reduce it to a single condition when it is not needed.None in a condition.ifIn lesson 6 you combined two conditions with and, or, and not. Real rules often contain more parts, and as the parts get mixed up, you need to know which operation Python does first. Let's start with a rule you already know: an order is accepted only if the item name is not empty and the quantity is greater than zero.
Example 1 (case): Validating an order
# 1. The order's information item = "latte" qty = 2 # 2. Are both rules met together? if item != "" and qty > 0: print("Order received") else: print("Missing information")
OutputOrder receivedPython reads this line like so: item != "" is true, and qty > 0 is true too. Because and needs both sides to be true, the result is true and the if block runs. If the quantity were 0, the second part would be false, and would give false, and the else block would run. Here there were two conditions and the order did not matter. With three parts, things change.
First a warm-up. At the café, the breakfast menu is valid from 9 to 12, and the evening menu after 18. At 2 p.m., is either of them valid? Predict without running the code.
What does this code print?
hour = 14 print(9 <= hour < 12 or hour >= 18)
Now a harder rule: "A student or a member who spends $5 or more gets a discount." When you read this sentence, you make "student or member" a group in your head, and then you look at the total. Python does not group the condition the way you do; it applies its own precedence rule. In lesson 3 you saw that in arithmetic, multiplication is done before addition: 2 + 3 * 4 is 14. Logic has a similar order: first not, then and, and or last. So and comes before or, just as multiplication comes before addition.
Example 2 (case): Parentheses change the result
student = True member = False total = 4 print(student or member and total >= 5) print((student or member) and total >= 5)
OutputTrue
FalseIn the first line there are no parentheses. Python first calculates the part member and total >= 5: because member is false, this part is false. Then student or False is calculated; because student is true, the result is True. So with this writing, a student gets a discount even on a $4 purchase; the rule did not want this. In the second line, the parentheses make Python calculate the group student or member first, which gives True. Then True and False is calculated and the result is false. This is exactly what the rule says: even if the group is true, there is no discount unless the total condition is met.
In the block below, change the two values and find in which case the two lines give different results.
When do the lines with and without parentheses differ? Change the values of student and total.
Pick a value; predict the output first, then look.
1student = True2member = False3total = 44print(student or member and total >= 5)5print((student or member) and total >= 5)
True False
Faded lines didn't run with this value. The two lines differ only when a student spends less than $5. Without parentheses, and is calculated first, and student alone makes the result true. When you test, try these kinds of splitting points on purpose.
Parentheses are useful even where Python would calculate in the same order anyway: they show the reader clearly what you mean. If the condition gets longer still, give its parts meaningful names. Put each part in a variable, then combine these names on the if line. That way the rule reads almost like an English sentence, and you can print the parts one by one to see which one came out false.
item = "latte" qty = 12 has_item = item != "" qty_valid = 1 <= qty <= 10 if has_item and qty_valid: print("Order received") else: print("Order does not meet the rules")
OutputOrder does not meet the rulesSome decisions are step by step: first you look at one question, and depending on its answer you ask a second question or never ask it. The cashier thinks this way too. They ask "Are you a member?"; if the answer is no, they never look at the total; if yes, they say one of two different things depending on the total. In Python, for this you write a second if inside an if block. The inner block is indented one more level, that is, four more spaces.
Example 3 (case): First membership, then total
member = True total = 8 if member: if total >= 5: print("Member discount: 10%") else: print("Member, no discount") else: print("Not a member")
OutputMember discount: 10%Python first looks at the outer condition, member. Because it is true, it enters the outer block and asks the inner condition, total >= 5. Because 8 is greater than 5, the first inner print runs. Pay attention to the two elses. The inner else is indented four spaces and belongs to the inner if; it covers the "member but low total" case. The outer else has no indentation and belongs to the outer if; it covers the "not a member" case. Only the indentation tells which else belongs to which if. Below, match the output for four different customers.
What does the code in Example 3 print for each customer?
For each row, pick its match from the list, then check.
Now build the same code yourself. The indentation matters as much as the order of the lines: the two else lines are told apart only by their indentation.
Put the lines of Example 3 in the right order with their indentation.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The nested form is not always necessary. Suppose the rule is only "write a discount message for a member who spends $5 or more, otherwise write nothing". Then the two forms below do the same job:
if member: if total >= 5: print("Member discount: 10%")
if member and total >= 5: print("Member discount: 10%")
The difference between them is this: in the nested form you can add an else for each step, while in the flat form there is a single else. If the in-between steps do not need separate messages, the nested form only adds indentation and lines. Code nested three or four levels deep is hard to read; writing the same decision in one line with and is both short and clear.
| Question | Nested form | Flat form (and) |
|---|---|---|
| Do the in-between steps need separate messages? | Yes: the inner and outer else say different things | No: a single else, or no else at all |
| Indentation level | One more level per step | A single level |
| When to choose it | "If not a member, this; if a member, this depending on the total" | "If all are true, do this" |
Compound conditions are used in elif chains too. In the code below, each branch asks several conditions at once. Follow it step by step and see why each condition came out true. Then, with "Change the code", set total to 6 and follow it again; this time none of the three conditions will hold.
Run the code line by line: see which line runs next, the variable boxes and the output.
age = 20 student = True total = 9 if student and total >= 8: discount = 20 elif age < 18 or total >= 15: discount = 10 else: discount = 0 print(discount)
NoneFields left blank on the order form reach Python as an empty string "". If a field was never sent at all, for example if the customer never opened the coupon box, its value is None. Catching each of these with separate comparisons such as != "" is both long and error-prone. Python has a shorter way: you can write a value directly in place of the condition.
When an if expects a condition, you do not have to give it True or False. If you give it any value, Python looks at whether that value counts as true or false. This is called the value's truthiness. The rule is one sentence: values that are "empty" or "zero" count as false, and everything else counts as true.
| Value | In a condition | Why |
|---|---|---|
0, 0.0 | False | Zero |
"" | False | Empty string |
None | False | No value |
5, -1, 0.5 | True | A number other than zero |
"no sugar", "0", " " | True | A non-empty string |
None in the table is a new value you meet in this lesson, and it means "no value yet". Its type is NoneType, and the only value of this type is None. None is not an empty string and not 0; it is only counted as false in a condition like them. To see how a value will count in a condition, you can use the bool() function: it takes a value and returns True or False.
Example 4 (case): An empty note and a coupon that was not entered
note = "" coupon = None print(bool(note), bool("no sugar"), bool(0), bool(coupon)) if not coupon: print("No coupon")
OutputFalse True False False
No couponbool(note) gives False because it is an empty string; "no sugar" gives True because it is not empty. bool(0) and bool(coupon) give False too. In the last two lines, not coupon reads as "if there is no coupon": because coupon counts as false, not turns it into true and No coupon is printed. The same line would also run if the coupon were an empty string; if not coupon: is a single condition for both None and "". Similarly, writing if note: means "if the note is not empty", and it is shorter than writing if note != "":.
So what does "not empty" mean? In the block below, change the value of the note. Pay special attention to the last two buttons: one is just a space, the other is a string that contains the digit zero.
Which notes count as "there"? Change the value of note.
Pick a value; predict the output first, then look.
1note = ""2if note:3 print(f"Has note: '{note}'")4else:5 print("No note")
No note
Faded lines didn't run with this value. Only "", which contains no characters at all, counts as false. A space is also a character; " " is a non-empty string. "0" is not a number either, it is a string with one character in it. You will learn how to clean a note written with only spaces in the string lessons.
With numbers, the situation sets a different trap. 0 is a valid number, but it counts as false in a condition. Predict what the code below prints.
What does this code print?
qty = 0 if qty: print("Quantity:", qty) else: print("No quantity entered")
This prediction shows an important distinction: "quantity 0" and "no quantity entered" are not the same thing. In a return, 0 can be a meaningful value; in that case counting 0 as "no value" is a mistake. To ask for None specifically, you use is None. is asks whether the two sides are the same value, and this is the right way for None; to ask the opposite, you write is not None.
qty = None if qty is None: print("No quantity entered") elif qty == 0: print("Quantity 0 entered") else: print("Quantity:", qty)
OutputNo quantity enteredNow it is your turn. First predict the output of the four lines in your head, then run them. Then add the lines print(bool(" ")), print(bool(0.0)), and print(bool(-1)) and run again.
Try it now· not graded; doesn't affect progress
Three ideas together: is the item empty (truthiness), is the quantity in range (a compound condition and not), was a coupon entered (None). The checks are made in order; it stops at the first error.
# 1. The order's information item = "" qty = 2 coupon = None # 2. Check in order, stop at the first error if not item: print("No item selected") elif not 1 <= qty <= 10: print("Quantity must be between 1 and 10") else: # 3. The order is fine; print the coupon if there is one print("Order received") if coupon: print("Coupon:", coupon)
OutputNo item selectedAs rules multiply, put them in a table: one situation and the expected output on each row. Then run the program once with the values of each row and compare the results. All the rows below were tried with this program; the boundary values (1, 10, 11) are in the table on purpose.
item |
|---|
Writing the second half of a condition without its subject. If you shorten the rule "the quantity is greater than 0 and less than 10" the way you would in English, Python raises an error:
qty = 5 if qty > 0 and < 10: print("Valid quantity")
Error:
Output if qty > 0 and < 10:
^
SyntaxError: invalid syntaxThe < 10 to the right of and does not say what is less than 10. Both sides of and must each be a complete condition on their own. The right way: if qty > 0 and qty < 10: or the chained if 0 < qty < 10:.
The item == "latte" or "tea" trap from lesson 6 is the same mistake, only it does not give an error message. The "tea" to the right of or is not a comparison, it is a non-empty string; by the truthiness rule it always counts as true. That is why, when item = "water", the line print(item == "latte" or "tea") prints tea and the if
and is calculated before or; a group built with "or" that will be tied to another condition is put in parentheses, and a long condition is split into parts with meaningful names.if is for step-by-step decisions; if the in-between steps do not need separate messages, the same decision is written with and in a single condition.0, 0.0, "", and None count as false in a condition, and everything else is true; "0" and " " are non-empty, and "never entered" is asked with is None.Next lesson: In the unit task, you will combine the hour, total, membership, and coupon rules in a single program.
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.
qtycoupon |
|---|
| Output |
|---|
"" | 2 | None | No item selected |
"latte" | 0 | None | Quantity must be between 1 and 10 |
"latte" | 11 | None | Quantity must be between 1 and 10 |
"latte" | 10 | None | Order received |
"latte" | 1 | "" | Order received |
"latte" | 2 | "CAFE20" | Order received / Coupon: CAFE20 |
The same pattern works on every form. On a gym's sign-up form, the name cannot be left blank, and people under 18 can sign up only with parental permission.
name = "" age = 17 parent_ok = False if not name: print("Name cannot be blank") elif age < 18 and not parent_ok: print("Parental permission required") else: print("Registration complete")
OutputName cannot be blankBecause the name is empty, the first branch runs and the other rules are not looked at. If name = "Alex", the second branch would be asked: 17 is less than 18, and not parent_ok is true too; the output would be Parental permission required.
item == "latte" or item == "tea"