- Learn
- Computer Science & IT
- Programming
- Introduction to Programming with Python
- Python If Statements
Python If Statements and Boolean Logic
and, or and not, and use if, elif and else to run the right code for each situation. Then nest decisions, use the truthiness of values, test every branch with well-chosen inputs, and choose among cases with the match statement.BeginnerLesson 2 of 10 in Python for Beginners: Introduction to Programming
What you will learn
- Write comparisons with Python's six comparison operators, predict whether they give
TrueorFalsefor numbers and text, and avoid the mix-ups that quietly make a condition wrong.- Compare numbers with the six comparison operatorsUse
==,!=,<,<=,>and>=to compare numbers, read each result as a Boolean value, and keep comparison apart from assignment. - Compare text, mixed types and rangesCompare strings exactly and in alphabetical order, convert typed input before comparing it with numbers, and test ranges, membership and
Nonewith the right operator.
- Compare numbers with the six comparison operators
- Write one-way, two-way and multi-way decisions so that a program runs the right block of code for each situation, and predict exactly which lines run for a given input.
- Run code only when a condition is trueWrite an
ifstatement with its header, colon and indented block, and trace which lines run and which are skipped. - Choose between two actions with if and elseAdd an
elsebranch so that exactly one of two blocks runs, and use a conditional expression to choose between two values in a single line. - Choose among several cases with elifBuild
if–elif–elsechains that test conditions in order, run only the first branch whose condition is true, and order the tests so every input lands in the right case.
- Run code only when a condition is true
- Join and negate conditions with
and,orandnot, predict their results with truth tables, and read longer conditions in the order Python evaluates them.- Join and negate conditions with and, or and notUse truth tables to predict
and,orandnot, translate everyday rules into combined conditions, and avoid the classicormistake. - Predict how Python evaluates longer conditionsApply operator precedence and short-circuit evaluation, add parentheses that make the intended grouping clear, and rewrite negated conditions with De Morgan's laws.
- Join and negate conditions with and, or and not
- Nest decisions where one choice depends on another, test values directly through their truthiness, and trace and test every branch so the logic holds for every input.
- Nest decisions inside other decisionsPlace an
ifstatement inside another branch when a second decision depends on the first, read nesting from its indentation, and flatten nesting whenandorelifsays the same thing more simply. - Test values directly with truthinessPredict which values Python treats as true or false in a condition, use this to test for empty input briefly, and avoid the traps where
0,"0"or"False"behave unexpectedly. - Trace and test every branch of a decisionTrace a decision by hand, choose test inputs that reach every branch and every boundary, and repair conditions that leave gaps, overlaps or branches that can never run.
- Nest decisions inside other decisions
- Use Python's
matchstatement to compare one value against several patterns, capture values and add guards, and decide whenmatchis clearer than anif–elifchain.- Match a value against fixed casesWrite a
matchstatement with literal patterns, alternatives and a wildcard, and predict which single case runs. - Capture values and add guards to casesUse capture patterns and
asto name the matched value, addifguards for conditions a literal cannot express, and avoid the trap where a variable name in a case matches everything.
- Match a value against fixed cases
Python If Statements study guide
1Comparisons that answer yes or no
A program needs a precise test before it can choose an action. Comparisons turn questions about values into answers Python can use: is the score high enough, does the answer match, or is the input inside a valid range? Numbers and text follow different comparison rules. Reading those rules carefully helps you catch mistakes that look reasonable on the screen, especially at a limit or when typed digits are still stored as text.
1.1 Numbers, equality, and limits
A comparison asks a question about values. Its result is a Boolean value: True or False. These are values of type bool, written with capital first letters and no quotes. "True" is text; lowercase true is a name and raises NameError when it has not been defined.
Choose the operator that matches the rule
| Operator | Question | With x = 7 |
|---|---|---|
== | Equal to? | x == 7 gives True |
!= | Not equal to? | x != 7 gives False |
< | Less than? | x < 7 gives False |
<= | Less than or equal to? | x <= 7 gives True |
> | Greater than? | x > 5 gives True |
>= | Greater than or equal to? | x >= 7 gives True |
The two-character operators stay together, with = last. Write <=, not =<. An integer and a float can compare equal: 7 == 7.0 gives True because their numeric values agree.
A comparison is an expression, so you can print its result or store it:
x = 7
is_big = x > 5
print(is_big)
Python evaluates x > 5, gets True, and assigns that value to is_big. The output is True. A name such as is_big or has_ticket makes a Boolean variable read like a yes/no question.
Keep assignment and comparison separate
x = 5 stores a new value in x. x == 5 checks the current value without changing it. Writing if x = 5: is a syntax error. The reverse mistake can be harder to notice:
x = 7
x == 5
print(x)
In a script, the comparison result is unused. The output remains 7; that middle line never assigns 5.
Work out arithmetic before comparing
In 2 + 3 > 4, Python first adds to get 5, then compares 5 > 4. The result is True. A useful whole-number test is n % 2 == 0: % gives the remainder after division, and even numbers leave remainder 0 when divided by 2.
For n = 10, the steps are 10 % 2, then 0 == 0, giving True. For n = -7, -7 % 2 is 1, so the even-number test is False. With the positive divisor 2, Python's remainder for an odd integer is 1, including a negative odd integer.
Decide whether the edge belongs
"At least 18" includes 18: age >= 18. "Over 18" excludes it: age > 18. Likewise, "under 13" is age < 13, and "no more than 3" is bags <= 3. Test the boundary itself when choosing an operator. At age = 18, the first age test is true and the second is false.
Allow for tiny float differences
Many decimal fractions have only approximate binary representations. Python stores 0.1 + 0.2 as 0.30000000000000004, so 0.1 + 0.2 == 0.3 is False.
For a comparison with an absolute tolerance of 1e-9, use:
print(abs((0.1 + 0.2) - 0.3) < 1e-9)
abs() gives the size of the difference without its sign. That difference is smaller than one billionth, so this test prints True. The tolerance states how much difference this check accepts; it is not exact equality.
Key Takeaways
- Comparisons produce the Boolean values
TrueandFalse. =assigns a value;==compares values without changing them.- Choose
<or<=, and>or>=, by whether the boundary is included. - Arithmetic happens before comparison, so
n % 2 == 0tests evenness. - Calculated floats may need a tolerance test instead of exact equality.
1.2 Text, typed numbers, and ranges
The values on both sides of a comparison matter as much as the operator. Text can look like a number while still following string rules.
Compare text exactly
String equality checks every character, including case and spaces. "yes" == "Yes" is False, and "yes" == "yes " is also False. To accept ordinary differences in capitalization and surrounding spaces, compare a cleaned copy:
answer = " Yes "
print(answer.strip().lower() == "yes")
strip() removes whitespace at both ends. lower() changes letters to lowercase. The cleaned text is "yes", so the result is True. The stored answer stays unchanged unless you assign the cleaned value to it.
Understand string order
Python compares strings from left to right using Unicode code points, the numbers assigned to characters. It stops at the first unequal pair. With unaccented English letters in the same case, this follows alphabetical order: "apple" < "banana" is True. When one string is the start of the other, the shorter comes first: "cat" < "catalog" is True.
This is not a full dictionary sorting rule. A through Z have code points 65–90, and a through z have 97–122. Thus "Zebra" < "apple" is True. The accented é also comes after z, so "zebra" < "éclair" is True.
Digits in strings follow the same character rule. "10" < "9" is True: the first comparison is between "1" and "9", not between the numbers ten and nine.
Convert input for numeric decisions
input() returns a string. If someone types 5, "5" == 5 gives False; equality does not convert the text. Ordering is different: "5" < 10 raises TypeError because Python cannot order that string and integer together.
age = int(input("Age: "))
print(age >= 18)
For the typed text "18", int() produces the integer 18, and the test prints True. Use float() when the input represents a decimal value.
Use a chain for a range
0 <= score <= 100 requires both neighboring comparisons to be true. It means 0 <= score and score <= 100. For score = 105, the lower test passes but the upper test fails, so the whole chain is False.
| Rule | Python test |
|---|---|
| From 1 through 10, including both ends | 1 <= x <= 10 |
| Strictly between 1 and 10 | 1 < x < 10 |
A chain compares neighbors only. 1 < 3 > 2 is True because 1 < 3 and 3 > 2 are both true; it does not compare 1 directly with 2.
Pick membership or identity when needed
The membership operators test whether text occurs inside text. "nan" in "banana" is True; "Ban" in "banana" is False. "x" not in "banana" is True.
None represents no value. Check it with result is None or result is not None. The operator is asks about the very same object, while == asks about equal values. Use == for numeric and string equality: an identity test such as x is 5 is unreliable for that purpose and produces a SyntaxWarning.
Key Takeaways
- String comparisons are case-sensitive and preserve spaces.
- Convert typed digits with
int()orfloat()before numeric comparisons. - A chained range requires every neighboring comparison to pass.
intests membership;is Nonetests for the no-value marker.
2Choosing the code that runs
A comparison becomes useful when it controls an action. Python marks each choice with a condition and an indented block, so the layout tells you which lines run together. Start with a block that may be skipped, then give it an alternative, and finally choose among several cases. The key is to follow the program in order: a later line may use a value set by an earlier branch, and a later test in one chain may never be reached.
2.1 The if header and its block
An if statement runs a block only when its condition is true. The header begins with if, gives the condition, and ends with a colon. The lines underneath are indented to show that they belong to its body.
Follow a one-way decision
temperature = 31
if temperature > 30:
print("Hot day")
print("Drink water")
print("Done")
At the header, Python reads the current value of temperature. The comparison 31 > 30 is True, so both indented lines run. The program then reaches the line outside the block. Its output is:
Hot day
Drink water
Done
Change the first line to temperature = 25. Now 25 > 30 is False, so Python skips the whole body. Only Done prints. The condition is tested once when Python reaches the header; an if does not keep checking it.
Let indentation show membership
By convention, use 4 spaces for each indentation level. Lines at the same level belong to the same block. Returning to the outer level ends it. If you indent print("Done") by 4 spaces, it moves into the if body and prints only when the condition passes.
A flowchart shows the same choice with a diamond. The True path enters the body, the False path goes around it, and the paths meet at the next statement outside the block.
| Problem | What to fix |
|---|---|
| Missing colon | End the header with :. |
| No indented body | Indent the lines controlled by if. |
| Inconsistent indentation | Align statements that belong to the same block. |
| Mixed tabs and spaces | Set the editor to insert spaces. |
Python may report SyntaxError, IndentationError, or TabError for these problems. Start with the header and the indentation around the reported line. Parentheses around the condition are optional; if temperature > 30: is the usual form.
A body cannot be empty. While leaving a place for an action, write an indented pass. It is a valid statement that does nothing:
if temperature > 30:
pass
Separate checks are independent
score = 95
if score >= 50:
print("Pass")
if score >= 90:
print("Excellent")
Python reaches both headers. Both conditions are true, so it prints both messages. Separate if statements fit rules whose actions can all apply to the same input.
Give later code a value it can use
A name assigned only in the body may never be created:
x = 0
if x > 0:
message = "positive"
print(message)
In a fresh script, the body is skipped and message has no value, so the last line raises NameError. One repair supplies a starting value before the choice:
x = 0
message = "not positive"
if x > 0:
message = "positive"
print(message)
Now the later line has a value on both paths. For zero it prints not positive; for a positive x, the body replaces that text with positive.
Key Takeaways
- An
ifheader ends with:, followed by an indented body. - A false condition skips the entire body; execution continues after it.
- Separate
ifstatements are each tested when reached. - Use an initial value or assign in every branch before reading a variable later.
passprovides a valid body that does nothing.
2.2 Two paths and a value to choose
An if–else statement chooses one of two blocks. When the condition is true, Python runs the if body. Otherwise it runs the else body. Exactly one runs when execution reaches this decision.
Align the alternatives
number = int(input("Enter a whole number: "))
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")
For input 14, the remainder is 0, so the output is 14 is even. For input -7, the remainder is 1, so the output is -7 is odd. The else belongs to the if at the same indentation level. Its body has its own indentation.
There is no condition after else: it means that the earlier condition was false. else number < 0: is a syntax error. Keep the clause directly after the if body; an unrelated unindented statement between the two breaks the structure.
Check what "everything else" includes
With if answer == "yes":, an else does not mean only "no". It also accepts "maybe", "Yes", and "", because none equals "yes". This is useful when every remaining input deserves the same action. If several rejected inputs need different responses, they need further tests.
Assign on both paths
A shipping rule gives free shipping for totals of at least 50 dollars and charges 5.99 dollars otherwise:
total = 42.50
if total >= 50:
shipping = 0
else:
shipping = 5.99
print(total + shipping)
First, 42.50 >= 50 gives False. Python skips the assignment of 0, runs the else, and stores 5.99. The last line is outside both bodies and prints 48.49. Change total to 60: the first body stores 0, the other is skipped, and the last line prints 60. Both routes define shipping before it is used.
Choose a value with a conditional expression
When the only difference is the value to assign, a conditional expression can say it in one line:
shipping = 0 if total >= 50 else 5.99
Its form is value_if_true if condition else value_if_false. Although the true value appears first on the page, Python evaluates the condition first. It evaluates only the chosen value, then assigns the result to shipping.
Another example is label = "even" if n % 2 == 0 else "odd". For n = 14, it selects "even". For n = -7, it selects "odd".
| Need | Suitable form |
|---|---|
| Several actions on either path | Full if–else blocks |
| One of two values | Conditional expression |
The expression requires both values. x = 1 if flag is incomplete and raises SyntaxError because there is no else value. A full if statement may omit else because it can simply take no action on the false path; an expression must still produce a value.
Key Takeaways
else:has no condition and aligns with itsif.- An
elsecovers every input rejected by the condition. - Assigning the same variable in both bodies makes it available after either path.
- A conditional expression has the form
a if condition else band evaluates only the selected value.
2.3 Several cases in a deliberate order
Use elif, short for "else if," to add another test to a decision. Python tries the conditions from top to bottom. The first true condition wins, and the rest of that chain is skipped.
Trace a grade decision
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(grade)
The first test, 85 >= 90, is false. The second, 85 >= 80, is true, so Python stores "B". It does not test the remaining conditions and does not enter else. The output is B.
| Score | First successful route | Grade |
|---|---|---|
90 | score >= 90 | A |
89 | score >= 80 | B |
60 | score >= 60 | D |
59 | Final else | F |
Use what earlier failures tell you
Reaching elif score >= 80: already tells you that the score is below 90. For whole-number scores, this branch covers 80 through 89. Adding and score < 90 would repeat a check the program has already settled.
The order matters because these ranges overlap. If score >= 60 comes first, it catches 85 and 95 before their higher-grade tests are reached. For lower-bound tests with >=, put the highest threshold first. For upper-bound tests with <, begin with the lowest threshold.
Keep one choice as one chain
Replacing the elif keywords with if changes the behavior. With a score of 85, the test for 80 assigns "B", the test for 70 then assigns "C", and the test for 60 assigns "D". The final value is "D". Each new if starts an independent decision.
This distinction also affects else. In a group of separate if statements, a final else belongs only to its matching if, not to the entire group. Keep the branches joined when they represent one classification.
Make room for boundaries and unmatched input
An elif chain may have any number of further tests, and its final else is optional. Without a catch-all, it may run no body:
temp = 20
if temp < 18:
print("Cool")
elif temp > 24:
print("Warm")
Neither condition passes. Add else: with an indented print("Comfortable") if every temperature needs a message. Likewise, t < 18 followed by t > 18 leaves exactly 18 unmatched. At grade thresholds, writing score > 90 would send 90 to the "B" branch.
Text menus use the same structure: test choice == "1", then choice == "2", and give anything else an "Unknown option" response. These checks compare strings because input() returns text. When many tests compare one value with fixed choices, match offers another way to lay out the decision.
Key Takeaways
- Only the first true branch of an
if–elifchain runs. - Earlier false tests narrow the inputs that can reach a later branch.
- Order overlapping thresholds so a broad test does not hide a narrower case.
- Separate
ifstatements can run several bodies and overwrite earlier assignments. - A final
elsehandles inputs that pass none of the tests. - Test exact thresholds to find gaps and off-by-one mistakes.
3Combining tests without changing the rule
Real decisions often depend on several facts at once: a range has two edges, and access may require both permission and an available place. Boolean operators join those facts into one condition. Their grouping and evaluation order also matter, because Python can stop before reaching part of a test. Translate the rule first, then follow the expression from left to right, keeping any parentheses and skipped work visible.
3.1 Both, either, and the opposite
The Boolean operators and, or, and not let you build a condition from simpler conditions. Python spells them as lowercase words.
Read all the possibilities
For Boolean inputs, and gives True only when both inputs are true. or gives True when at least one is true, including when both are true. This is an inclusive or.
A | B | A and B | A or B |
|---|---|---|---|
True | True | True | True |
True | False | False | True |
False | True | False | True |
False | False | False | False |
not reverses a truth value: not True gives False, and not False gives True. A truth table lists every combination of Boolean inputs. Two inputs need four rows; three need eight. Each extra independent Boolean input doubles the combinations.
For A and not B, first reverse B, then combine it with A. In the row A = True, B = False, not B is True, so the result is True. The other three rows give False.
Translate a rule into complete tests
A museum discounts admission for visitors under 12 or aged 65 and over:
has_discount = age < 12 or age >= 65
At age 10, the first comparison passes. At 65, the second passes. Ages 30 and 64 pass neither. Using and would require the same age to be under 12 and at least 65, which cannot happen.
A ride requires a height of at least 120 centimeters and no heart condition:
can_ride = height >= 120 and not has_heart_condition
The two requirements must hold together. At the minimum height with has_heart_condition = False, both parts pass. If either requirement fails, can_ride is False.
Distinguish inside from outside a range
| Meaning | Test |
|---|---|
| Inside 0 through 100 | score >= 0 and score <= 100 |
| Outside 0 through 100 | score < 0 or score > 100 |
The inside test needs both limits. The outside test needs either failure. score < 0 and score > 100 can never be true for one number.
Each comparison needs both sides. score >= 0 and <= 100 is incomplete syntax. A subtler problem runs without an error:
if answer == "y" or "yes":
print("Accepted")
Python sees (answer == "y") or "yes". When the comparison is false, the non-empty string "yes" still makes the condition truthy. Repeat the comparison: answer == "y" or answer == "yes".
Everyday wording needs the same care. "Closed on Saturday and Sunday" means day == "Saturday" or day == "Sunday"; one day need not be both names at once. For a Boolean variable, negate it directly with not is_member. A negated comparison such as not (age >= 18) can also be written more simply as age < 18. Python's operators here are words, not &&, ||, or !.
Key Takeaways
andrequires both Boolean inputs; inclusiveorrequires at least one.notreverses a truth value and always produces a Boolean.- Inside a range needs
and; outside it needsor. - Repeat the full comparison on each side of a Boolean operator.
- A truth table checks every combination, including the case where both inputs are true.
3.2 Grouping, skipped work, and negation
A longer condition has two questions to settle: how its parts are grouped, and which parts Python actually evaluates. Operator precedence answers the first. Short-circuit evaluation answers the second.
Read the grouping first
For the operators used here, precedence goes from tighter to looser:
- Exponentiation:
**. - Multiplication, division, floor division, remainder:
*,/,//,%. - Addition and subtraction:
+,-. - Comparisons, including
in,not in,is, andis not. not, thenand, thenor.- The conditional expression:
a if condition else b.
Parentheses change the grouping. For example, x > 3 or x < 0 and x != 5 groups as x > 3 or (x < 0 and x != 5). At x = 5, the left comparison is true and the whole right-hand group is skipped. The result is True.
With (x > 3 or x < 0) and x != 5, the parentheses instead make the first group one operand of and. At x = 5, that group is true, but x != 5 is false, so the result is False.
This is why is_weekend or is_holiday and is_sunny accepts every weekend, even in rain. For the rule "a day off that is also sunny," write (is_weekend or is_holiday) and is_sunny.
Follow evaluation from left to right
| Expression | When Python skips B |
|---|---|
A and B | A is falsy |
A or B | A is truthy |
For and, a false first part has already ruled out the whole requirement. For or, a true first part has already met it. Precedence does not force Python to calculate a skipped operand just because it contains tighter operators.
You can use this to place a guard before an operation that would fail:
count = 0
total = 50
is_large_average = count != 0 and total / count > 10
print(is_large_average)
count != 0 is false, so Python never attempts 50 / 0. It stores and prints False. Reversing the operands attempts the division first and raises ZeroDivisionError; the later check cannot protect earlier work.
Push not through a grouped test
De Morgan's laws rewrite a negation by reversing each part and switching the joining operator:
| Original | Equivalent |
|---|---|
not (A and B) | not A or not B |
not (A or B) | not A and not B |
"Not a teenager" can be tested as not (age >= 13 and age <= 19). The equivalent direct test is age < 13 or age > 19. Ages 12 and 20 pass; 13, 16, and 19 do not.
Keeping and after negating both parts changes the rule. At A = True, B = False, not (A and B) is true, but not A and not B is false. Compare every truth-table row when checking two Boolean forms for equivalence.
For a variable that already holds a Boolean, write if is_valid: or if not is_valid:. Comparing it with True or False adds a test the condition does not need.
Key Takeaways
- Precedence groups an expression; short-circuiting determines which operands are reached.
andskips its right operand after a falsy left operand;orskips it after a truthy left operand.- Put a protective guard before the operation it protects.
- De Morgan’s laws negate both parts and switch
andwithor. - Use parentheses to show the intended grouping when mixing
andandor. - Test Boolean variables directly with their name or
not.
4Making decisions easy to trace and test
A decision can depend on another decision, and a value can act as a condition without an explicit comparison. Both make scripts shorter, but they also create paths that are easy to overlook. Indentation shows which checks depend on earlier choices; truthiness explains how empty text and zero behave. Tracing those paths and testing exact boundaries lets you find missing responses, overwritten values, and branches that no input can reach.
4.1 Decisions inside other branches
A nested conditional puts one decision inside a branch of another. The inner decision is reached only when execution enters that outer branch. Each nesting level adds 4 spaces of indentation.
Trace the outer choice before the inner choice
has_ticket = True
age = 15
if has_ticket:
if age >= 13:
print("Enjoy the movie")
else:
print("This movie needs an adult")
else:
print("Please buy a ticket first")
First, has_ticket is true, so Python enters the outer body. Then it tests 15 >= 13, gets true, and prints Enjoy the movie. The inner and outer else bodies are both skipped.
Change the age to 10 while keeping the ticket. Python still enters the outer body, but the inner condition fails, so it prints This movie needs an adult. With has_ticket = False, the age test is never reached; the outer else prints Please buy a ticket first.
Pair each else by indentation
An else belongs to the if at its own indentation level. Moving it can change the behavior even if the script remains valid. Consider this smaller variant:
if has_ticket:
if age >= 13:
print("Enter")
else:
print("Buy a ticket")
The else belongs to if has_ticket:. A 10-year-old with a ticket gets no message. Move that else and its body inward one level, and it belongs to if age >= 13: instead. Now the same child gets Buy a ticket, while someone without a ticket gets no message. The changed layout expresses a different rule.
In the full movie example, the inner if already has an else. Moving the outer else inward there would create two alternatives for the same if and cause a syntax error.
Flatten a pair of requirements
When there is only one action and neither level has an else, and often removes a nesting level:
if is_member and total >= 50:
print("Free shipping")
This runs the same action as an outer if is_member: containing an inner if total >= 50:. Both requirements must pass, and the second is reached only after the first passes. Keep nesting when the outer branches need their own different actions, as with buying a ticket.
An else whose only action is another if–else can become an elif chain. For positive, negative, and zero, the flat form is if x > 0:, then elif x < 0:, then else:. It keeps the same three outcomes with less indentation.
Validate before classifying
A grade decision needs to reject scores outside its allowed range before assigning a letter:
if 0 <= score <= 100:
if score >= 90:
print("A")
else:
print("Below A")
else:
print("Score must be between 0 and 100")
At score = 150, the outer check fails, so no grade is assigned. Nesting also exposes impossible paths: an inner if x < 5: under if x > 10: can never pass. When indentation grows deep, look for combined requirements, an elif chain, or an earlier validation check that makes the remaining paths clearer.
Key Takeaways
- An inner condition is tested only after its outer branch is entered.
- Indentation determines which
ifowns anelse. - Two nested requirements with one action and no alternatives can become one
andcondition. - Validate the allowed range before assigning a category.
- Contradictory inner and outer requirements create unreachable code.
4.2 Empty, zero, and values used as conditions
Python can test a value directly in a condition. Its truthiness decides whether the body runs. This saves comparisons, but the value's truthiness may differ from what its text seems to say.
Recognize falsy values
For the built-in types here, False, None, numeric zero, empty strings, and empty collections are falsy. Nonzero numbers and non-empty strings or collections are truthy.
| Value | bool(value) | Why |
|---|---|---|
0, 0.0 | False | Numeric zero |
-3 | True | Nonzero number |
"" | False | Empty string |
" " | True | Contains a space |
"0", "False", "no" | True | Non-empty strings |
None | False | No-value marker |
[], (), {} | False | Empty collections |
bool() converts a value to its Boolean truth value. In a condition, if value: makes the same branch choice as if bool(value):. It does not change the stored value into a Boolean.
Test empty input without misreading it
name = input("Name: ")
if name:
print("Hello", name)
else:
print("No name entered")
Pressing Enter without typing gives "", so the second body runs. A name made entirely of spaces is non-empty and passes the first test. if name.strip(): instead tests the text after removing surrounding whitespace, so a spaces-only answer fails too.
A yes/no answer needs a different question. if answer: runs for "no" and "False" because both contain characters. To recognize agreement, compare the text, for example answer == "yes". Truthiness checks emptiness, not the meaning of a word.
Keep a valid zero separate from missing data
Suppose quantity is None before a value is supplied and may legitimately be 0. if quantity: rejects both. Use quantity is not None to ask whether a value is present; this accepts zero.
For an actual Boolean variable, direct testing is clear. For other values, x == True does something different from if x:. With x = 5, the truthiness test passes but 5 == True is false; numeric equality treats True as equal to 1, not to every nonzero number.
and and or return a value they inspect
These operators return an operand, which may not be a Boolean:
| Expression | Returned value |
|---|---|
"" or "Guest" | "Guest" |
"Ana" or "Guest" | "Ana" |
0 and 5 | 0 |
3 and 5 | 5 |
For or, Python returns the left value if it is truthy; otherwise it evaluates and returns the right value. For and, it returns the left value if it is falsy; otherwise it evaluates and returns the right value.
display_name = name or "Guest" supplies a default for empty input. The same pattern with quantity or 1 replaces a real zero with 1. Use a default this way only when every falsy value means missing. not behaves differently: it always returns True or False. If a stored flag must be Boolean, has_name = bool(name or nickname) converts the selected text to a truth value.
Key Takeaways
- Empty built-in containers and text, zero,
None, andFalseare falsy. - Non-empty strings remain truthy even when they say
"0"or"False". - Use
is not Nonewhen zero is a valid supplied value. andandorreturn operands;notalways returns a Boolean.- An
ordefault replaces every falsy left value, including zero. strip()makes a spaces-only input empty before testing it.
4.3 Tracing paths and testing the edges
A script can run without a syntax error and still choose the wrong branch. Tracing follows one execution by hand. Testing runs chosen inputs and compares the observed result with the result the rule requires.
Plan and trace a path
Before writing code, state the choices in plain-language steps, or pseudocode. A flowchart puts each condition in a diamond with True and False arrows. Both paths need a clear next step or end.
To trace code, write the starting values, evaluate each reached condition, record assignments, and copy the output exactly. For the grade chain at score = 72:
| Reached condition | Result | Action |
|---|---|---|
score >= 90 | False | Continue to the next test |
score >= 80 | False | Continue to the next test |
score >= 70 | True | Set grade to "C" |
| Remaining chain | Not evaluated | Continue after the chain |
"Not evaluated" is different from false. Python has already selected a branch, so it does not need the later comparisons.
Cover every branch and boundary
A four-branch chain needs at least four inputs to make every branch run once. Pick them by the intended routes, not by how varied the numbers look. Several high scores may all exercise the same first body.
Branch coverage alone can miss a wrong boundary. For age >= 18, test 17, 18, and 19. A mistaken > passes the outer two checks just as expected but rejects the exact limit. For a grade threshold of 90, compare 89, 90, and 91; do the same at the other thresholds. For decimal inputs, choose nearby values appropriate to the measurement's precision.
Find branches that cannot run
if score >= 60:
print("Pass")
elif score >= 90:
print("Excellent")
The second branch is unreachable. Any score at least 90 already passed the first test. Put the more restrictive threshold first, or change the ranges to match the intended rule.
A gap leaves an intended case unhandled: t < 0 followed by t > 0 skips zero. An overlap can make several independent actions run: separate tests t >= 0 and t <= 10 both pass for 5. A chain permits only its first true branch, but its order still decides which overlapping condition wins.
Include awkward inputs
Test negative values, zero, empty text, and uppercase answers when the script expects lowercase. If only "y" and "n" are accepted, give any other text a clear response such as "Please answer y or n".
When a test behaves unexpectedly, inspect the value and its type before evaluating the suspect comparison:
print(repr(age), type(age))
For age = "18", this prints '18' <class 'str'>. Convert the text before trying age >= 18; putting the faulty comparison inside that same debugging print() would raise TypeError before the diagnostic output appears. For structural problems, inspect indentation and the syntax error message.
Finally, a comparison can set a Boolean flag directly: is_adult = age >= 18. It replaces two branches whose only assignments are True and False. Use bool() when the underlying expression may return a different kind of value.
Key Takeaways
- Trace only conditions the program reaches, and record skipped tests as skipped.
- Test every branch plus the boundary and nearby values of each limit.
- Earlier broad tests can make later branches unreachable.
- Check gaps, overlaps, and unexpected inputs against the intended rule.
- Inspect the value and its type before evaluating a comparison that may fail.
5Choosing cases with match
Menus and commands often compare one value with several fixed choices. A match statement lays those choices out as patterns and runs the first successful case. Literal values, alternatives, and a final wildcard handle many simple menus. Captures and guards add flexibility, but a name inside a pattern behaves differently from a name in a comparison. Learning that distinction prevents a case from accidentally accepting every input.
5.1 Fixed values, alternatives, and a catch-all
A match statement, available in Python 3.10 and later, tries one value against a series of patterns. That value is the subject. Each case supplies a pattern and an indented body.
Follow the first matching case
command = "stop"
match command:
case "start":
print("Starting")
case "stop":
print("Stopping")
case _:
print("Unknown command")
print("Ready")
The subject is "stop". It does not match "start", so Python tries the next case. "stop" matches, and the body prints Stopping. Python then leaves the entire match and prints Ready. Only one case body runs; there is no fall-through into the next body and no break is needed.
A subject of "jump" reaches the final wildcard pattern, _, which accepts any value. The output is Unknown command, then Ready. Without that case, an unmatched subject simply runs no case body and continues after the statement.
Keep the layout and catch-all in order
The case headers are indented 4 spaces under match, and their bodies another 4 spaces. Every header ends with a colon. An unguarded case _: must be last, because it accepts everything. Putting more cases after it raises SyntaxError: those later patterns could never be reached.
A guarded wildcard can appear earlier because its extra condition may fail. A match in a straight-line script also cannot contain break; that statement requires a surrounding loop.
Understand how literals match
A literal pattern uses a fixed number, string, True, False, or None. String patterns are exact and case-sensitive: "stop" does not match "Stop". Numeric patterns use equality, so case 1: matches 1, 1.0, and True, which equals 1.
The patterns True, False, and None use identity instead. Thus case True: matches the Boolean True but not integer 1. Pattern order matters if a numeric case and a Boolean case could both accept the subject.
Join fixed alternatives with a bar
An OR pattern joins alternatives with |:
day = int(input("Day number: "))
match day:
case 6 | 7:
print("Weekend")
case 1 | 2 | 3 | 4 | 5:
print("Weekday")
case _:
print("Not a day number")
For 6, the first body runs; for 3, the second runs; for 9, the wildcard runs. Without int(), typed "6" stays a string and does not match numeric 6.
Use the pattern separator |, not the Boolean word or. case "y" or "yes": is invalid; case "y" | "yes": is valid.
| Decision | Clear starting choice |
|---|---|
| One subject compared with many fixed values | match |
Ranges such as score >= 90 | if–elif |
| Conditions involving different variables | if–elif |
For fixed commands, an equality-based if–elif chain can produce the same outputs. Choose the layout that makes the cases easiest to read.
Key Takeaways
matchneeds Python 3.10 or later and runs the first successful case only.- An unguarded wildcard
_accepts everything and must be last. - Use
|to join alternative patterns. - String and numeric literals match by equality;
True,False, andNonepatterns use identity. - Unmatched subjects run no body when no catch-all is present.
- Use
matchfor fixed choices andif–eliffor ordinary range tests.
5.2 Captures, guards, and named values
Patterns can do more than check a fixed literal. A pattern may give the subject a name, and a guard may check an extra condition before the case is accepted.
Capture first, then check the guard
A capture pattern is a bare name such as n. It accepts any subject and assigns that subject to the name. A guard follows the pattern with if condition; the body runs only if the pattern matches and the guard is true.
temperature = -5
match temperature:
case 0:
print("Exactly freezing")
case t if t < 0:
print("Below freezing by", -t, "degrees")
case _:
print("Above freezing")
At -5, the first literal does not match. The next pattern captures -5 in t, then tests t < 0. The guard is true, so the output is Below freezing by 5 degrees.
At 0, the literal case wins before the capture is tried. At 12, the capture succeeds but the guard fails, so Python tries the wildcard and prints Above freezing. A failed guard does not end the search for a case.
A bare name does not look up a constant
Suppose QUIT = "q". It is tempting to write case QUIT: to check whether the subject equals that value. But a bare name is always a capture, even when uppercase. The case accepts any subject and overwrites QUIT with it.
If further cases follow an unguarded capture, Python reports a syntax error because the capture makes them unreachable. If the capture is last, the mistake can run silently. Compare explicitly with a guard:
QUIT = "q"
key = "x"
match key:
case k if k == QUIT:
print("Quit")
case _:
print("Keep working")
Here k captures "x". The guard compares it with the existing "q", fails, and lets the wildcard print Keep working. A literal case "q": is simpler when the fixed value can be written directly.
Distinguish a dotted value pattern
A dotted name such as math.pi is a value pattern, not a capture. It looks up an existing value and compares the subject with it using ==. Named constants supplied by modules or classes can use this form. The distinction to recognize is the dot: case n: assigns a name; a dotted pattern checks an existing value.
Name a successful specific match with as
answer = "y"
match answer:
case "y" | "yes" as accepted:
print("Accepted:", accepted)
case _:
print("Please answer y or yes")
The OR pattern checks the allowed strings, and as stores the subject that matched in accepted. For "y", the output is Accepted: y. It does not replace the input with a standard word: "yes" would store "yes". "Yes" matches neither string because case still matters.
One or two guards can fit naturally among fixed cases. When almost every case is a range test or uses different variables, an if–elif chain is usually clearer. Either structure needs a final catch-all when every input must receive a response.
Key Takeaways
- A bare-name pattern captures the subject even if that name already has a value.
- A guard is checked after a pattern matches; a false guard allows later cases to be tried.
- A dotted value pattern compares with an existing value.
asnames the subject accepted by a more specific pattern.- Use a literal or guarded comparison to avoid accidental constant-name capture.
Python If Statements examples
1Turn values into reliable comparisons
13 steps
- 1IntroductionA storage limit needs an exact test
A storage locker accepts packages weighing from 1 through 8 kilograms, including both limits. Before choosing an action, the program must turn that rule into a yes/no answer, a Boolean produced by a comparison, so that every later decision rests on an exact test.
Start with individual comparisons, then combine the two edges into a range. Along the way, check whether a value is a number or merely text that looks numeric.
- 2ExplanationA comparison produces a Boolean
With
weight = 8, the expressionweight < 8isFalse: eight is not less than itself. The expressionweight <= 8isTrue, because it includes equality.Both results have type
bool. WriteTrueandFalsewith capitals and no quotes. Text such as"True"is a string, and an undefined lowercasetrueraisesNameErrorinstead of supplying a Boolean. - 3ExampleStore the result without changing the weight
weight = 8 fits_upper_limit = weight <= 8 print(weight, fits_upper_limit)First,
8 <= 8evaluates toTrue. The assignment stores that Boolean infits_upper_limit; the original weight is unchanged. The output is8 True.The single
=performs the assignment. The comparison uses<=; for a question about equal values, use==. - 4ChallengeDoes a comparison update the value?
Predict the output:
weight = 6 weight == 8 print(weight)---reveal---
It prints
6. The middle line compares the current weight with 8 but never assigns a replacement value. In a script its false result is unused. A singleweight = 8assignment would change the final output to8. - 5ConnectionArithmetic can supply the value to compare
A whole-number test can compare an arithmetic result:
n % 2 == 0first finds the remainder after division by 2, then checks equality with zero.For
n = -9, the remainder is1, so the test is false. Python's remainder with positive divisor 2 is1for odd integers even when the original integer is negative. Comparing the remainder with1tests oddness. - 6TipCalculated floats can be slightly apart
0.1 + 0.2is stored as0.30000000000000004, so its exact equality test against0.3fails.A tolerance check asks a different question:
abs((0.1 + 0.2) - 0.3) < 1e-9tests whether the distance is smaller than one billionth.abs()removes the sign of the difference. This test is true; it accepts a tiny discrepancy instead of claiming exact equality. - 7ExampleTyped digits start as text
weight = input("Weight in kilograms: ")If the user types
8, the variable contains"8". Comparingweight <= 8raisesTypeError, because it tries to order a string and an integer.Read a decimal measurement with
weight = float(input("Weight in kilograms: ")). The same typed digits now produce8.0, which can be compared numerically with8. - 8ExplanationStrings follow characters from the left
Text order is based on Unicode code points.
"18" < "8"is true because the first unequal pair is"1"and"8"; Python does not treat those strings as eighteen and eight.Case and spaces also matter.
"ready" == "Ready"is false. Comparinganswer.strip().lower()with"ready"removes surrounding whitespace and normalizes capitalization before the equality check. - 9ChallengeCheck what membership actually asks
Evaluate these two tests:
"box" in "mailbox" "Box" in "mailbox"---reveal---
The first is
True, and the second isFalse. Membership looks for the exact substring, including capitalization. The letters"box"occur together at the end of"mailbox"; the capital"B"does not occur there.not inwould reverse each result. - 10ExampleCheck both ends of the locker rule
weight = 8 fits_locker = 1 <= weight <= 8 print(fits_locker)The chain checks
1 <= 8and8 <= 8. Both pass, so the result isTrue. Atweight = 0.5, the lower test fails; at8.5, the upper test fails.Every neighboring comparison in a chain must pass. Replacing either
<=with<excludes that endpoint. - 11Key InsightMissing data is a different question
Nonemeans no value is present. Check it withweight is Noneorweight is not None.The operator
isasks whether references identify the same object. Numeric equality uses==, so do not replaceweight == 8withweight is 8. Values can be equal without being the same object, and an identity comparison with a numeric literal produces a warning. - 12ChallengeCombine conversion with a boundary check
A script runs
weight = float(input("Weight: ")), and the user types"8.5". What does1 <= weight <= 8return, and does the conversion itself reject the input?---reveal---
It returns
Falsebecause8.5 <= 8fails. The conversion succeeds: 8.5 is a valid float. Converting text establishes a numeric type; the range test separately decides whether that number is allowed. - 13RecapThree questions to keep separate
Choose the operator to match the boundary, establish the value's type, and then trace the comparison.
Numeric ordering needs numeric values. String checks preserve exact characters unless you clean the text. A range needs both edges, membership asks about a substring, and identity is the right tool for checking
None.
2Follow a delivery choice through its branches
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFrom a rule to a path through code
- 2ExampleA warning that may be skipped
- 3TipFix structure before interpreting results
- 4ChallengeMove the last line into the body
- 5ExampleGive the false path an action
- 6Key InsightElse means every rejected input
- 7ExampleChoose just the fee in one expression
- 8ChallengeRead the values around the condition
- 9ExampleLay out three service bands
- 10ExampleUse the earlier failure to narrow the range
- 11ChallengeChange the order of overlapping tests
- 12ConnectionA new if is a new decision
- 13ChallengeFind both the label and the fee
- 14RecapMatch the structure to the choice
3Build and protect a combined condition
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeveral facts can control one action
- 2ExplanationRequire both facts with and
- 3ExampleAllow either payment with or
- 4ChallengeChoose a row that passes
- 5TipGive each comparison its own operands
- 6ExamplePut alternatives inside the shared requirement
- 7Key InsightGrouping is not the execution order
- 8ExamplePut a guard before an average
- 9ChallengeWhich work is reached?
- 10ExplanationNegating a range changes the connector
- 11ChallengePreserve the included endpoints
- 12ChallengeTranslate two requirements and one exclusion
- 13RecapRead meaning, grouping, then reached work
4Validate, classify, and test a delivery request
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionEvery input needs the intended path
- 2ExampleValidate before choosing a service
- 3ExampleTrace the inner path
- 4ChallengeFind the owner of else
- 5ConnectionFlatten when there is one shared action
- 6ExplanationZero and missing are both falsy
- 7ExampleText that looks negative can still pass
- 8ChallengeKeep a real zero
- 9Key InsightAn operator can select text
- 10ExampleRecord a path without inventing tests
- 11TipChoose tests for paths and boundaries
- 12ChallengeA broad condition hides a later branch
- 13ConnectionLook for gaps and unintended overlaps
- 14TipInspect the value before a risky comparison
- 15ChallengeTest a corrected decision completely
- 16RecapGive values and tests a clear purpose
5Match commands and add guarded cases
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionOne subject, several possible cases
- 2ExampleLay out the command menu
- 3Key InsightThe next case does not run automatically
- 4ExampleUse one body for two exact commands
- 5ChallengePlace the fallback where it can help
- 6TipCheck numeric and Boolean pattern behavior
- 7ExplanationA bare name captures any subject
- 8ExampleAdd a guard to the captured value
- 9ChallengeContinue after a false guard
- 10ExampleAn uppercase name still captures
- 11ConnectionA dot changes lookup behavior
- 12ExampleName a successful literal alternative
- 13ChallengeChoose a menu structure for the task
- 14ChallengeKeep a fixed name and allow a fallback
- 15RecapRead patterns before reading case bodies
Python If Statements practice questions
Set 1: Read comparisons and follow decisions10 Practice Questions
Question 1 of 10
bool("no") return?Show answerHide answer
"no" contains characters, so its truth value is true. bool() converts that truthiness to the Boolean True; it does not interpret the word as a refusal. Returning false would confuse a non-empty string with a Boolean answer about its meaning.Question 2 of 10
visits of at least 24. A programmer wrote visits > 24. What input most directly exposes the wrong result?Show answerHide answer
>= 24 and > 24, so either alone would miss this mistake. Testing the exact boundary distinguishes the two operators.Question 3 of 10
What is printed?
mode = "SAVE"
match mode:
case "save" | "write":
print("Stored")
case _:
print("Unknown")
print("End")
Show answerHide answer
"SAVE" does not equal either lowercase literal because string matching is case-sensitive. The wildcard prints Unknown, and the line after the match prints End. Printing Stored would assume pattern matching normalizes capitalization automatically.Question 4 of 10
weight?Show answerHide answer
weight <= 6 accepts 6 as well as smaller weights. The strict test weight < 6 rejects a parcel at exactly the allowed limit. The direction must also accept smaller weights, so a greater-than test reverses the rule.Question 5 of 10
"14" < "7" evaluate to?Show answerHide answer
"1" precedes "7", making this comparison true without comparing the numeric values 14 and 7. The numeric interpretation would apply only after converting the strings to numbers.Question 6 of 10
What is printed?
stock = 0
if stock > 0:
print("Available")
print("Checked")
Show answerHide answer
0 > 0 is false, so Python skips the indented print. The final print is outside the body and still runs, producing Checked. Skipping all output would incorrectly treat that unindented statement as part of the conditional body.Question 7 of 10
What value is assigned to fee?
has_pass = False
fee = 2 if has_pass else 7
Show answerHide answer
has_pass is false, so fee becomes 7. Choosing 2 would read the first written value as the default instead of the value reserved for a true condition.Question 8 of 10
What is printed?
points = 46
if points >= 50:
print("Gold")
elif points >= 30:
print("Silver")
elif points >= 10:
print("Bronze")
else:
print("Starter")
Show answerHide answer
Silver and leaves the chain. Although 46 also meets the bronze threshold, that later condition is skipped; a chain does not run every body whose condition could be true.Question 9 of 10
Show answerHide answer
or accepts a subscription, a day pass, or both, and rejects only the case with neither. Using and would require both forms of access at once. The rule names alternatives that independently allow the download, so that extra requirement would reject valid users.Question 10 of 10
total and items, a flag should be true only when an average exceeds 8. Zero items must give false without attempting division. What expression implements both requirements?Show answerHide answer
and, so zero items stops evaluation before division and gives false. With nonzero items, Python evaluates the average test. Putting the division first fails at zero; using or either accepts zero or skips the average for nonzero counts.Set 2: Apply rules and diagnose wrong branches10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
is_open and not is_full true?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
What Boolean value is stored in is_odd?
n = -13
is_odd = n % 2 == 1
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
level = input("Level: "). The user types 16. What happens when it next evaluates level < 20?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
What is the final value of label?
points = 37
if points >= 30:
label = "High"
if points >= 10:
label = "Middle"
else:
label = "Low"
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
What is printed?
is_open = False
has_booking = True
if is_open:
if has_booking:
print("Enter")
else:
print("Book first")
else:
print("Closed")
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
"" or "Reader" return?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
"edit" or "change" into one body?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
What is printed?
value = 11
match value:
case n if n < 0:
print("Negative", n)
case n if n % 2 == 0:
print("Even", n)
case _:
print("Other")
Show answerHide answer
Save this lesson to see this answer.
Set 3: Trace values through several decisions10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
None means no count was supplied. What assignment uses a default of 9 only for missing data?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
This integer classifier should print exactly one sign label for every integer. What input reveals a missing case?
if balance < 0:
print("Negative")
elif balance > 0:
print("Positive")
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
What is printed?
reply = "later"
match reply:
case "now" | "later" as chosen:
print(chosen)
case _:
print("Unknown")
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
not (-4 <= reading <= 9)?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
What happens to EXIT?
EXIT = "x"
key = "z"
match key:
case EXIT:
print(EXIT)
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
a = 0.1 + 0.2 and a target is b = 0.3. The check must accept differences smaller than 1e-8. What test implements it?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
What is printed?
remaining = 4
if remaining > 0:
remaining = 0
if remaining == 0:
print("Empty")
print(remaining)
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
What value is assigned to label?
has_booking = True
label = "Reserved" if has_booking else "Open"
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
What happens when this expression is evaluated?
is_admin = True
count = 0
total = 18
is_admin or count != 0 and total / count > 6
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
What is printed, and why?
has_badge = True
is_active = False
if has_badge:
if is_active:
print("Enter")
else:
print("Get a badge")
print("Checked")
Show answerHide answer
Save this lesson to see this answer.
Set 4: Repair and test combined decision rules10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
"go" despite surrounding whitespace and capitalization differences. It must reject "gopher" and "stop". What condition implements this?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
What is printed?
units = 0
amount = 15
result = amount / units if units != 0 else "No units"
print(result)
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
"High" for points of at least 70, "Mid" for 35 through 69, and "Low" below 35. Tests use >= in one chain. What branch order and labels implement the rule?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
wired and wireless, is available, and maintenance is off. What condition implements the whole rule?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
"High"; other valid scores need "Low"; invalid scores need "Invalid". A script classifies with if score >= 9: and else: but never validates the range. What structure repairs it for every integer score?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
What value is stored in chosen?
preferred = ""
alternate = "Morgan"
chosen = preferred or alternate or "Visitor"
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
For integer scores, a classifier should use "Top" for at least 80, "Pass" for 40 through 79, and "Retry" below 40. Which test input exposes an error in this code?
if score >= 40:
print("Pass")
elif score >= 80:
print("Top")
else:
print("Retry")
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
What is printed?
value = True
match value:
case 1:
print("Number case")
case True:
print("Boolean case")
case _:
print("Other case")
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
case n ___ n > 4:?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
As pattern
case "y" | "yes" as reply: stores "y" when that is the string supplied.Assignment
=, replacing any value already associated with that name.score = 28 changes score; writing score == 28 only compares its current value.B
Block
print() calls under a temperature test are in the block that the test controls.Boolean operator
and, or, and not for these operations.has_ticket and is_open into one test.Boolean value
True and False, which Python uses to express the result of a yes/no test.is_ready = count >= 4 is True when count equals 4.Boundary-value test
age >= 18.Branch coverage
C
Capture pattern
case STOP: overwrites STOP; uppercase spelling does not make it a lookup.Case guard
if condition after a pattern that must pass before its body runs; a false guard allows later cases to be tried.case n if n < 0: checks the captured number before choosing the negative case.Case-sensitive comparison
"Yes" when the exact required text is "yes".Catch-all branch
else in a multi-way conditional statement."Unknown option" for menu input other than "1" or "2".Chained comparison
2 <= level <= 9 includes 2 and 9 but rejects a level of 10.Comparison operator
<= does when it includes a limit.weight <= 8 accepts a weight of exactly 8 kilograms.Conditional expression
a if condition else b, evaluating only the selected value.fee = 0 if has_pass else 4 stores 4 when the pass is absent.Conjunction
and that passes only when both requirements pass, such as the two edges of a range.age >= 13 and age <= 19 rejects ages on either side of the teenage range.D
De Morgan’s laws
and with or, preserving its truth value.not (A or B) into not A and not B, with both parts reversed.Default value
or expression."Guest" is selected in name or "Guest" when name is the empty string.E
Elif clause
if chain and is considered only after every earlier condition has failed.Else branch
if condition is false; the else: header has no condition.if test for even numbers, the else branch runs for -7, because its remainder is not zero.Equivalent conditions
not (age >= 18) and age < 18 agree for every whole-number age.F
Falsy value
None, False, empty text, and empty built-in collections.quantity or 1 choose the default even if zero was entered intentionally.First-match rule
>= 60 if that broad test appears first.Flattening
and condition.Flowchart
I
Identity test
is or is not to check whether references identify the same object, commonly to recognize None.result is None distinguishes a missing result from a real value of zero.If statement
if stock > 0: skips its body when stock is zero.Inclusive boundary
<= or >= in a numeric comparison.age >= 18 lets a person aged exactly 18 pass the test.Inclusive or
or follows this meaning.is_member or has_coupon pass when both a membership and a coupon are present.Indentation
print("Done") inside an if body makes it run after the whole decision.Input validation
0 <= score <= 100 rejects 150 before a grade can be assigned.L
Literal pattern
None; numeric and string literals compare by equality.case 6: accepts numeric 6 but rejects the text "6" returned by input.M
Match statement
"stop" skips case "start": and runs the body under case "stop":.Membership operator
in and not in test exact substrings."rain" in "raincoat" finds the text and returns True.N
Nested conditional
O
Operand
and and or return one of their operands instead of always a Boolean."" or "Guest" is falsy, so the expression returns the right operand.Operator precedence
and grouping before or.A or B and C as A or (B and C) unless parentheses change it.OR pattern
| and succeeds when any alternative matches, sharing one case body.case "open" | "load": runs the same body for either command string.Outer condition
has_ticket is false, the inner age comparison is skipped.P
Pass statement
if body valid without producing output.Protective guard
count != 0 before the division in count != 0 and total / count > 10.Pseudocode
S
Short-circuit evaluation
total / count after a false count != 0 test joined by and.Subject
match in the header.match command:, the current value of command is the subject used for every case attempt.T
Threshold
score >= 90.Tolerance
1e-9 lets abs(a - b) < 1e-9 accept a tiny difference between calculated floats.Trace table
Truth table
Truthiness
if name: reject an empty answer without an explicit comparison with "".Truthy value
"False" passes if answer: because its characters make the string non-empty.Two-way decision
if and else, with a body to run for either truth value.Type conversion
int() before comparing sizes.level = int(input("Level: ")) makes a numeric limit test possible.U
Unicode code point
"Z" is smaller than that for "a", so "Zebra" < "apple" is true.Unreachable branch
elif score >= 90: follows the broader if score >= 60:.V
Value pattern
math.pi compares with an existing module value instead of assigning a bare name.W
Wildcard pattern
_, which accepts any subject without naming it; an unguarded wildcard case must appear last."Unknown command" when earlier fixed command patterns fail.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.