Python If Statements and Boolean Logic

Learn how a Python program makes decisions. Compare numbers and text with comparison operators, join conditions with 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

  1. Write comparisons with Python's six comparison operators, predict whether they give True or False for numbers and text, and avoid the mix-ups that quietly make a condition wrong.
    • Compare numbers with the six comparison operators
      Use ==, !=, <, <=, > and >= to compare numbers, read each result as a Boolean value, and keep comparison apart from assignment.
    • Compare text, mixed types and ranges
      Compare strings exactly and in alphabetical order, convert typed input before comparing it with numbers, and test ranges, membership and None with the right operator.
  2. 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 true
      Write an if statement with its header, colon and indented block, and trace which lines run and which are skipped.
    • Choose between two actions with if and else
      Add an else branch 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 elif
      Build if–elif–else chains 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.
  3. Join and negate conditions with and, or and not, predict their results with truth tables, and read longer conditions in the order Python evaluates them.
    • Join and negate conditions with and, or and not
      Use truth tables to predict and, or and not, translate everyday rules into combined conditions, and avoid the classic or mistake.
    • Predict how Python evaluates longer conditions
      Apply operator precedence and short-circuit evaluation, add parentheses that make the intended grouping clear, and rewrite negated conditions with De Morgan's laws.
  4. 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 decisions
      Place an if statement inside another branch when a second decision depends on the first, read nesting from its indentation, and flatten nesting when and or elif says the same thing more simply.
    • Test values directly with truthiness
      Predict 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 decision
      Trace 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.
  5. Use Python's match statement to compare one value against several patterns, capture values and add guards, and decide when match is clearer than an if–elif chain.
    • Match a value against fixed cases
      Write a match statement with literal patterns, alternatives and a wildcard, and predict which single case runs.
    • Capture values and add guards to cases
      Use capture patterns and as to name the matched value, add if guards for conditions a literal cannot express, and avoid the trap where a variable name in a case matches everything.

Python If Statements study guide

5 chapters

1

Comparisons 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
OperatorQuestionWith 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 True and False.
  • = 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 == 0 tests 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.

RulePython test
From 1 through 10, including both ends1 <= x <= 10
Strictly between 1 and 101 < 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() or float() before numeric comparisons.
  • A chained range requires every neighboring comparison to pass.
  • in tests membership; is None tests for the no-value marker.
2

Choosing 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.

ProblemWhat to fix
Missing colonEnd the header with :.
No indented bodyIndent the lines controlled by if.
Inconsistent indentationAlign statements that belong to the same block.
Mixed tabs and spacesSet 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 if header ends with :, followed by an indented body.
  • A false condition skips the entire body; execution continues after it.
  • Separate if statements are each tested when reached.
  • Use an initial value or assign in every branch before reading a variable later.
  • pass provides 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".

NeedSuitable form
Several actions on either pathFull if–else blocks
One of two valuesConditional 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 its if.
  • An else covers 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 b and 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.

ScoreFirst successful routeGrade
90score >= 90A
89score >= 80B
60score >= 60D
59Final elseF
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–elif chain 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 if statements can run several bodies and overwrite earlier assignments.
  • A final else handles inputs that pass none of the tests.
  • Test exact thresholds to find gaps and off-by-one mistakes.
3

Combining 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.

ABA and BA or B
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse

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
MeaningTest
Inside 0 through 100score >= 0 and score <= 100
Outside 0 through 100score < 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

  • and requires both Boolean inputs; inclusive or requires at least one.
  • not reverses a truth value and always produces a Boolean.
  • Inside a range needs and; outside it needs or.
  • 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:

  1. Exponentiation: **.
  2. Multiplication, division, floor division, remainder: *, /, //, %.
  3. Addition and subtraction: +, -.
  4. Comparisons, including in, not in, is, and is not.
  5. not, then and, then or.
  6. 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
ExpressionWhen Python skips B
A and BA is falsy
A or BA 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:

OriginalEquivalent
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.
  • and skips its right operand after a falsy left operand; or skips it after a truthy left operand.
  • Put a protective guard before the operation it protects.
  • De Morgan’s laws negate both parts and switch and with or.
  • Use parentheses to show the intended grouping when mixing and and or.
  • Test Boolean variables directly with their name or not.
4

Making 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 if owns an else.
  • Two nested requirements with one action and no alternatives can become one and condition.
  • 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.

Valuebool(value)Why
0, 0.0FalseNumeric zero
-3TrueNonzero number
""FalseEmpty string
" "TrueContains a space
"0", "False", "no"TrueNon-empty strings
NoneFalseNo-value marker
[], (), {}FalseEmpty 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:

ExpressionReturned value
"" or "Guest""Guest"
"Ana" or "Guest""Ana"
0 and 50
3 and 55

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, and False are falsy.
  • Non-empty strings remain truthy even when they say "0" or "False".
  • Use is not None when zero is a valid supplied value.
  • and and or return operands; not always returns a Boolean.
  • An or default 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 conditionResultAction
score >= 90FalseContinue to the next test
score >= 80FalseContinue to the next test
score >= 70TrueSet grade to "C"
Remaining chainNot evaluatedContinue 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.
5

Choosing 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.

DecisionClear starting choice
One subject compared with many fixed valuesmatch
Ranges such as score >= 90if–elif
Conditions involving different variablesif–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

  • match needs 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, and None patterns use identity.
  • Unmatched subjects run no body when no catch-all is present.
  • Use match for fixed choices and if–elif for 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.
  • as names the subject accepted by a more specific pattern.
  • Use a literal or guarded comparison to avoid accidental constant-name capture.

Python If Statements examples

5 Walkthroughs

1

Turn values into reliable comparisons

13 steps
Follow a storage-limit check from numeric comparisons to typed input, text checks, and an inclusive range.
  1. 1
    IntroductionA 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.

  2. 2
    ExplanationA comparison produces a Boolean

    With weight = 8, the expression weight < 8 is False: eight is not less than itself. The expression weight <= 8 is True, because it includes equality.

    Both results have type bool. Write True and False with capitals and no quotes. Text such as "True" is a string, and an undefined lowercase true raises NameError instead of supplying a Boolean.

  3. 3
    ExampleStore the result without changing the weight
    weight = 8
    fits_upper_limit = weight <= 8
    print(weight, fits_upper_limit)
    

    First, 8 <= 8 evaluates to True. The assignment stores that Boolean in fits_upper_limit; the original weight is unchanged. The output is 8 True.

    The single = performs the assignment. The comparison uses <=; for a question about equal values, use ==.

  4. 4
    ChallengeDoes 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 single weight = 8 assignment would change the final output to 8.

  5. 5
    ConnectionArithmetic can supply the value to compare

    A whole-number test can compare an arithmetic result: n % 2 == 0 first finds the remainder after division by 2, then checks equality with zero.

    For n = -9, the remainder is 1, so the test is false. Python's remainder with positive divisor 2 is 1 for odd integers even when the original integer is negative. Comparing the remainder with 1 tests oddness.

  6. 6
    TipCalculated floats can be slightly apart

    0.1 + 0.2 is stored as 0.30000000000000004, so its exact equality test against 0.3 fails.

    A tolerance check asks a different question: abs((0.1 + 0.2) - 0.3) < 1e-9 tests 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.

  7. 7
    ExampleTyped digits start as text
    weight = input("Weight in kilograms: ")
    

    If the user types 8, the variable contains "8". Comparing weight <= 8 raises TypeError, 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 produce 8.0, which can be compared numerically with 8.

  8. 8
    ExplanationStrings 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. Comparing answer.strip().lower() with "ready" removes surrounding whitespace and normalizes capitalization before the equality check.

  9. 9
    ChallengeCheck what membership actually asks

    Evaluate these two tests:

    "box" in "mailbox"
    "Box" in "mailbox"
    

    ---reveal---

    The first is True, and the second is False. 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 in would reverse each result.

  10. 10
    ExampleCheck both ends of the locker rule
    weight = 8
    fits_locker = 1 <= weight <= 8
    print(fits_locker)
    

    The chain checks 1 <= 8 and 8 <= 8. Both pass, so the result is True. At weight = 0.5, the lower test fails; at 8.5, the upper test fails.

    Every neighboring comparison in a chain must pass. Replacing either <= with < excludes that endpoint.

  11. 11
    Key InsightMissing data is a different question

    None means no value is present. Check it with weight is None or weight is not None.

    The operator is asks whether references identify the same object. Numeric equality uses ==, so do not replace weight == 8 with weight is 8. Values can be equal without being the same object, and an identity comparison with a numeric literal produces a warning.

  12. 12
    ChallengeCombine conversion with a boundary check

    A script runs weight = float(input("Weight: ")), and the user types "8.5". What does 1 <= weight <= 8 return, and does the conversion itself reject the input?

    ---reveal---

    It returns False because 8.5 <= 8 fails. 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.

  13. 13
    RecapThree 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.

2

Follow a delivery choice through its branches

14 steps
Build a delivery decision from a single if to two alternatives, a selected value, and ordered service bands.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFrom a rule to a path through code
  2. 2
    ExampleA warning that may be skipped
  3. 3
    TipFix structure before interpreting results
  4. 4
    ChallengeMove the last line into the body
  5. 5
    ExampleGive the false path an action
  6. 6
    Key InsightElse means every rejected input
  7. 7
    ExampleChoose just the fee in one expression
  8. 8
    ChallengeRead the values around the condition
  9. 9
    ExampleLay out three service bands
  10. 10
    ExampleUse the earlier failure to narrow the range
  11. 11
    ChallengeChange the order of overlapping tests
  12. 12
    ConnectionA new if is a new decision
  13. 13
    ChallengeFind both the label and the fee
  14. 14
    RecapMatch the structure to the choice
3

Build and protect a combined condition

13 steps
Translate a booking rule, group alternatives, use short-circuit guards, and negate a range correctly.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeveral facts can control one action
  2. 2
    ExplanationRequire both facts with and
  3. 3
    ExampleAllow either payment with or
  4. 4
    ChallengeChoose a row that passes
  5. 5
    TipGive each comparison its own operands
  6. 6
    ExamplePut alternatives inside the shared requirement
  7. 7
    Key InsightGrouping is not the execution order
  8. 8
    ExamplePut a guard before an average
  9. 9
    ChallengeWhich work is reached?
  10. 10
    ExplanationNegating a range changes the connector
  11. 11
    ChallengePreserve the included endpoints
  12. 12
    ChallengeTranslate two requirements and one exclusion
  13. 13
    RecapRead meaning, grouping, then reached work
4

Validate, classify, and test a delivery request

16 steps
Follow nested checks, preserve valid zero values, and build tests that expose gaps and wrong thresholds.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionEvery input needs the intended path
  2. 2
    ExampleValidate before choosing a service
  3. 3
    ExampleTrace the inner path
  4. 4
    ChallengeFind the owner of else
  5. 5
    ConnectionFlatten when there is one shared action
  6. 6
    ExplanationZero and missing are both falsy
  7. 7
    ExampleText that looks negative can still pass
  8. 8
    ChallengeKeep a real zero
  9. 9
    Key InsightAn operator can select text
  10. 10
    ExampleRecord a path without inventing tests
  11. 11
    TipChoose tests for paths and boundaries
  12. 12
    ChallengeA broad condition hides a later branch
  13. 13
    ConnectionLook for gaps and unintended overlaps
  14. 14
    TipInspect the value before a risky comparison
  15. 15
    ChallengeTest a corrected decision completely
  16. 16
    RecapGive values and tests a clear purpose
5

Match commands and add guarded cases

15 steps
Build a command menu, trace a guarded number match, and distinguish capture names from existing constants.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionOne subject, several possible cases
  2. 2
    ExampleLay out the command menu
  3. 3
    Key InsightThe next case does not run automatically
  4. 4
    ExampleUse one body for two exact commands
  5. 5
    ChallengePlace the fallback where it can help
  6. 6
    TipCheck numeric and Boolean pattern behavior
  7. 7
    ExplanationA bare name captures any subject
  8. 8
    ExampleAdd a guard to the captured value
  9. 9
    ChallengeContinue after a false guard
  10. 10
    ExampleAn uppercase name still captures
  11. 11
    ConnectionA dot changes lookup behavior
  12. 12
    ExampleName a successful literal alternative
  13. 13
    ChallengeChoose a menu structure for the task
  14. 14
    ChallengeKeep a fixed name and allow a fallback
  15. 15
    RecapRead patterns before reading case bodies

Python If Statements practice questions

40 Practice Questions in 4 sets

Set 1: Read comparisons and follow decisions10 Practice Questions

Question 1 of 10

What does bool("no") return?
  1. The string "no"
  2. False
  3. True
  4. The value None
Show answerHide answer
Answer: C
The string "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

An integer rule should accept visits of at least 24. A programmer wrote visits > 24. What input most directly exposes the wrong result?
  1. 23
  2. 25
  3. 24
  4. 26
Show answerHide answer
Answer: C
The intended rule accepts 24, but the written strict comparison rejects it. Inputs 23 and 25 behave the same under >= 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")
  1. Only Stored
  2. Unknown, then End
  3. Stored, then End
  4. Only Unknown
Show answerHide answer
Answer: B
The subject "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

A parcel may weigh at most 6 kilograms. What test accepts exactly the allowed weights using weight?
  1. weight < 6
  2. weight >= 6
  3. weight <= 6
  4. weight > 6
Show answerHide answer
Answer: C
"At most" includes the maximum, so 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

What does "14" < "7" evaluate to?
  1. False, because 14 exceeds 7.
  2. True, because "1" precedes "7".
  3. False, because the strings differ.
  4. True, because two digits exceed one.
Show answerHide answer
Answer: B
Both operands are strings, so Python compares characters from the left. The character "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")
  1. Only Available
  2. Available, then Checked
  3. Nothing is printed
  4. Only Checked
Show answerHide answer
Answer: D
The comparison 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
  1. 7
  2. 2
  3. False
  4. 0
Show answerHide answer
Answer: A
A conditional expression checks its condition first and selects its false-side value when the condition fails. Here 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")
  1. Silver, then Bronze
  2. Only Silver
  3. Only Bronze
  4. Only Starter
Show answerHide answer
Answer: B
The first comparison fails because 46 is below 50. The next comparison passes, so Python prints 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

A download can start if a user has a subscription or has a day pass, including users who have both. What condition implements the rule?
  1. has_subscription or has_day_pass
  2. has_subscription and has_day_pass
  3. not has_subscription and has_day_pass
  4. not (has_subscription or has_day_pass)
Show answerHide answer
Answer: A
Inclusive 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

For numeric 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?
  1. total / items > 8 and items != 0
  2. items == 0 or total / items > 8
  3. items != 0 or total / items > 8
  4. items != 0 and total / items > 8
Show answerHide answer
Answer: D
The nonzero check must be on the left of 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

What pair of Boolean inputs makes is_open and not is_full true?
  1. is_open = False, is_full = False
  2. is_open = True, is_full = True
  3. is_open = False, is_full = True
  4. is_open = True, is_full = False
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
  1. False, because n is negative.
  2. False, because the remainder is -1.
  3. True, because every nonzero number is odd.
  4. True, because the remainder is 1.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A program reads level = input("Level: "). The user types 16. What happens when it next evaluates level < 20?
  1. It raises TypeError.
  2. It evaluates to True.
  3. It evaluates to False.
  4. It changes level to 20.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What is Python’s dedicated no-action statement for an unfinished branch?
  1. else
  2. elif
  3. pass
  4. if
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"
  1. "High"
  2. "Middle"
  3. "Low"
  4. "High Middle"
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A booking is allowed only on a weekday and only if the user has credit or a voucher. What expression applies that rule?
  1. is_weekday and (has_credit or has_voucher)
  2. is_weekday and has_credit and has_voucher
  3. (is_weekday and has_credit) or has_voucher
  4. is_weekday or (has_credit and has_voucher)
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")
  1. Only Book first
  2. Only Closed
  3. Enter, then Closed
  4. Nothing is printed
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What value does "" or "Reader" return?
  1. The empty string ""
  2. The Boolean False
  3. The string "Reader"
  4. The Boolean True
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What case header sends either string "edit" or "change" into one body?
  1. case "edit" | "change":
  2. case "edit" or "change":
  3. case "edit" and "change":
  4. case "edit" == "change":
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")
  1. Negative 11
  2. Even 11
  3. Nothing is printed
  4. Only 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

A zero is a valid supplied count, and None means no count was supplied. What assignment uses a default of 9 only for missing data?
  1. count = supplied or 9
  2. count = 9 if not supplied else supplied
  3. count = supplied if supplied else 9
  4. count = 9 if supplied is None else supplied
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")
  1. 0
  2. -1
  3. 1
  4. 2
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")
  1. now
  2. later
  3. Unknown
  4. True
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A sensor accepts numeric readings from -4 through 9, inclusive. What condition is equivalent to not (-4 <= reading <= 9)?
  1. reading <= -4 or reading >= 9
  2. reading < -4 and reading > 9
  3. reading >= -4 and reading <= 9
  4. reading < -4 or 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)
  1. It stays "x", and nothing prints.
  2. It stays "x", and x prints.
  3. It becomes "z", and z prints.
  4. It becomes True, and True prints.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A calculation gives 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?
  1. a == b
  2. abs(a - b) > 1e-8
  3. abs(a - b) < 1e-8
  4. abs(a + b) < 1e-8
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)
  1. Empty, then 0
  2. Only 0
  3. Empty, then 4
  4. Only 4
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"
  1. True
  2. "Open"
  3. False
  4. "Reserved"
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
  1. It raises ZeroDivisionError immediately.
  2. It returns True without dividing.
  3. It returns False without dividing.
  4. It divides after checking count.
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")
  1. Get a badge, then Checked; the inner test fails.
  2. Enter, then Checked; the badge test passes.
  3. Only Checked; the outer else is skipped.
  4. Only Get a badge; the inner else runs.
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

A prompt accepts "go" despite surrounding whitespace and capitalization differences. It must reject "gopher" and "stop". What condition implements this?
  1. answer.strip().lower() in "go"
  2. answer.strip().lower() == "go"
  3. "go" in answer.strip().lower()
  4. answer.strip() == "go"
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)
  1. Only No units
  2. Only 0
  3. Only 15
  4. A ZeroDivisionError is raised.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

For whole-number points, a rating is "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?
  1. >= 35: Mid; >= 70: High; else: Low
  2. >= 70: High; >= 35: Low; else: Mid
  3. >= 35: High; >= 70: Mid; else: Low
  4. >= 70: High; >= 35: Mid; else: Low
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A service should run only when at least one of two connections, wired and wireless, is available, and maintenance is off. What condition implements the whole rule?
  1. wired or wireless and not maintenance
  2. wired and wireless and not maintenance
  3. (wired or wireless) and not maintenance
  4. (wired or wireless) or not maintenance
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Scores are integers from 0 through 12. Valid scores of at least 9 need "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?
  1. Check score >= 0 outside; classify inside; otherwise print Invalid.
  2. Check 0 <= score <= 12 outside; classify inside; otherwise print Invalid.
  3. Check score <= 12 outside; classify inside; otherwise print Invalid.
  4. Classify first; then check 0 <= score <= 12 and print Invalid if it fails.
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"
  1. "Morgan"
  2. "Visitor"
  3. True
  4. ""
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")
  1. 39
  2. 40
  3. 79
  4. 80
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")
  1. Only Boolean case
  2. Number case, then Boolean case
  3. Only Number case
  4. Only Other case
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A four-branch chain prints one of four labels. Four different inputs all print the first label. How many branches have these tests covered?
  1. One branch
  2. Two branches
  3. Three branches
  4. Four branches
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What keyword introduces the extra condition after a pattern in case n ___ n > 4:?
  1. and
  2. if
  3. as
  4. elif
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

55 Key Terms, each with its definition

A

As pattern
An as pattern names the subject accepted by a more specific pattern, preserving the actual value that matched for use in the body.
The as pattern in case "y" | "yes" as reply: stores "y" when that is the string supplied.
Assignment
An assignment stores a value under a variable name using =, replacing any value already associated with that name.
The assignment score = 28 changes score; writing score == 28 only compares its current value.

B

Block
A block is a group of statements at the same indentation level that Python treats as the body of a conditional or other statement.
Two indented print() calls under a temperature test are in the block that the test controls.
Boolean operator
A Boolean operator combines or reverses truth values; Python uses the lowercase words and, or, and not for these operations.
A Boolean operator joins the two requirements in has_ticket and is_open into one test.
Boolean value
A Boolean value is one of the two values True and False, which Python uses to express the result of a yes/no test.
The Boolean value stored by is_ready = count >= 4 is True when count equals 4.
Boundary-value test
A boundary-value test checks a limit and nearby inputs to detect a comparison that includes or excludes the wrong endpoint.
A boundary-value test uses 17, 18, and 19 to check a whole-number rule written as age >= 18.
Branch coverage
Branch coverage checks whether chosen tests have executed each branch at least once, including fallback and nested branches.
Branch coverage for a four-branch chain needs at least four inputs that take different routes.

C

Capture pattern
A capture pattern is a bare name that accepts any subject and assigns it to that name, even when the name already stores a value.
The capture pattern case STOP: overwrites STOP; uppercase spelling does not make it a lookup.
Case guard
A case guard is an if condition after a pattern that must pass before its body runs; a false guard allows later cases to be tried.
The case guard in case n if n < 0: checks the captured number before choosing the negative case.
Case-sensitive comparison
A case-sensitive comparison treats uppercase and lowercase letters as different characters when checking text for equality or order.
A case-sensitive comparison rejects "Yes" when the exact required text is "yes".
Catch-all branch
A catch-all branch handles inputs that earlier cases did not accept, such as a final else in a multi-way conditional statement.
A catch-all branch can print "Unknown option" for menu input other than "1" or "2".
Chained comparison
A chained comparison joins neighboring comparisons in one expression and passes only when every comparison in the chain passes.
The chained comparison 2 <= level <= 9 includes 2 and 9 but rejects a level of 10.
Comparison operator
A comparison operator checks values for equality or order and produces a Boolean result, as <= does when it includes a limit.
The comparison operator in weight <= 8 accepts a weight of exactly 8 kilograms.
Conditional expression
A conditional expression selects and produces one of two values using a if condition else b, evaluating only the selected value.
The conditional expression fee = 0 if has_pass else 4 stores 4 when the pass is absent.
Conjunction
A conjunction is a condition joined with and that passes only when both requirements pass, such as the two edges of a range.
The conjunction age >= 13 and age <= 19 rejects ages on either side of the teenage range.

D

De Morgan’s laws
De Morgan’s laws rewrite a negated Boolean group by negating each part and switching and with or, preserving its truth value.
De Morgan’s laws change not (A or B) into not A and not B, with both parts reversed.
Default value
A default value is a fallback used when a preferred value is absent or unsuitable, such as text selected by an or expression.
The default value "Guest" is selected in name or "Guest" when name is the empty string.

E

Elif clause
An elif clause adds another conditional branch to an if chain and is considered only after every earlier condition has failed.
The elif clause for scores of at least 80 is reached only after the test for 90 fails.
Else branch
An else branch is the alternative body that runs when its matching if condition is false; the else: header has no condition.
In an if test for even numbers, the else branch runs for -7, because its remainder is not zero.
Equivalent conditions
Equivalent conditions give the same truth value for every allowed combination of their inputs, even when their written forms differ.
Equivalent conditions not (age >= 18) and age < 18 agree for every whole-number age.

F

Falsy value
A falsy value is a value that makes a condition fail, including zero, None, False, empty text, and empty built-in collections.
A falsy value of zero makes quantity or 1 choose the default even if zero was entered intentionally.
First-match rule
The first-match rule selects the earliest successful branch in one decision chain and skips all remaining conditions and bodies.
By the first-match rule, a score of 95 is caught by >= 60 if that broad test appears first.
Flattening
Flattening rewrites nested decisions with fewer indentation levels while keeping the same branch choices and actions.
Flattening two checks with one shared action can replace the nesting with an and condition.
Flowchart
A flowchart is a diagram of program paths that shows a decision as a diamond with separate True and False routes to the next action.
A flowchart shows both routes rejoining after the body of a one-way temperature decision.

I

Identity test
An identity test uses is or is not to check whether references identify the same object, commonly to recognize None.
The identity test result is None distinguishes a missing result from a real value of zero.
If statement
An if statement checks a condition and runs its indented body only when the condition is truthy, then continues after that body.
The if statement headed by if stock > 0: skips its body when stock is zero.
Inclusive boundary
An inclusive boundary is a limit that belongs to the accepted range, expressed with <= or >= in a numeric comparison.
The inclusive boundary in age >= 18 lets a person aged exactly 18 pass the test.
Inclusive or
An inclusive or accepts either alternative and also accepts both together; Python’s Boolean or follows this meaning.
Inclusive or lets is_member or has_coupon pass when both a membership and a coupon are present.
Indentation
Indentation is the leading space that marks which block a statement belongs to; Python convention uses 4 spaces per level.
Removing one level of indentation from print("Done") inside an if body makes it run after the whole decision.
Input validation
Input validation checks whether supplied data meets the program’s allowed rules before the data is used for a further decision.
Input validation with 0 <= score <= 100 rejects 150 before a grade can be assigned.

L

Literal pattern
A literal pattern checks a fixed number, string, Boolean, or None; numeric and string literals compare by equality.
The literal pattern case 6: accepts numeric 6 but rejects the text "6" returned by input.

M

Match statement
A match statement tries one subject against ordered case patterns and executes only the first successful case body, then continues.
The match statement for "stop" skips case "start": and runs the body under case "stop":.
Membership operator
A membership operator tests whether a value occurs within another value; for strings, in and not in test exact substrings.
The membership operator in "rain" in "raincoat" finds the text and returns True.

N

Nested conditional
A nested conditional is a conditional inside another branch, so its test is reached only when execution enters that outer branch.
The nested conditional checks a visitor’s age only after the outer ticket check succeeds.

O

Operand
An operand is a value or expression an operator works on; and and or return one of their operands instead of always a Boolean.
The left operand of "" or "Guest" is falsy, so the expression returns the right operand.
Operator precedence
Operator precedence determines how an expression groups its operators without extra parentheses, with and grouping before or.
Operator precedence reads A or B and C as A or (B and C) unless parentheses change it.
OR pattern
An OR pattern joins alternative patterns with | and succeeds when any alternative matches, sharing one case body.
The OR pattern case "open" | "load": runs the same body for either command string.
Outer condition
An outer condition controls entry into a block that contains another decision, deciding whether the inner test is reached at all.
When the outer condition has_ticket is false, the inner age comparison is skipped.

P

Pass statement
A pass statement is a valid statement that performs no action, allowing a required block to exist before its useful code is written.
An indented pass statement keeps an unfinished if body valid without producing output.
Protective guard
A protective guard is a check placed before an operation so short-circuit evaluation can prevent that operation when it would fail.
A protective guard tests count != 0 before the division in count != 0 and total / count > 10.
Pseudocode
Pseudocode describes program steps in plain language, making the intended choices clear before they are written in Python syntax.
Pseudocode can say "Reject an out-of-range score; otherwise assign its grade" before coding.

S

Short-circuit evaluation
Short-circuit evaluation skips a later Boolean operand when the left operand has already settled whether the condition passes.
Short-circuit evaluation skips total / count after a false count != 0 test joined by and.
Subject
The subject is the value a match statement checks against its case patterns, written after the keyword match in the header.
In match command:, the current value of command is the subject used for every case attempt.

T

Threshold
A threshold is a value at which a decision changes outcome, with the comparison operator deciding which side includes that value.
A grade threshold of 90 assigns 90 to the higher band when the test is score >= 90.
Tolerance
A tolerance is the amount of difference a numeric check accepts when calculated values may contain small approximation errors.
A tolerance of 1e-9 lets abs(a - b) < 1e-9 accept a tiny difference between calculated floats.
Trace table
A trace table records variable values, reached conditions, and actions in execution order so a program’s path can be followed by hand.
A trace table marks later grade tests as skipped after an earlier branch assigns the grade.
Truth table
A truth table lists every combination of Boolean inputs and the result for each, making a compound condition possible to check fully.
A truth table for two inputs has four rows, including the case where both inputs are true.
Truthiness
Truthiness is the truth value Python uses when a general value appears in a condition, allowing numbers or text to control a branch.
Truthiness lets if name: reject an empty answer without an explicit comparison with "".
Truthy value
A truthy value is a value that makes a condition pass, including nonzero numbers and non-empty strings, even strings that say false.
The truthy value "False" passes if answer: because its characters make the string non-empty.
Two-way decision
A two-way decision chooses exactly one of two paths using if and else, with a body to run for either truth value.
A two-way decision assigns a shipping charge on both paths before the total is printed.
Type conversion
A type conversion creates a value of another type, such as turning digit text into an integer with int() before comparing sizes.
Type conversion in level = int(input("Level: ")) makes a numeric limit test possible.

U

Unicode code point
A Unicode code point is the number assigned to a character; Python uses these numbers when comparing strings from left to right.
The Unicode code point for "Z" is smaller than that for "a", so "Zebra" < "apple" is true.
Unreachable branch
An unreachable branch is a branch no input can enter because earlier decisions or contradictory requirements always prevent it.
An unreachable branch results when elif score >= 90: follows the broader if score >= 60:.

V

Value pattern
A value pattern is a dotted name that looks up an existing value and compares the subject with it using equality, without capturing.
The value pattern math.pi compares with an existing module value instead of assigning a bare name.

W

Wildcard pattern
A wildcard pattern is _, which accepts any subject without naming it; an unguarded wildcard case must appear last.
A wildcard pattern prints "Unknown command" when earlier fixed command patterns fail.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started