Decisions and Validation Study Guide: Fundamentals of Programming

Workbook Overview and Pedagogical Framework

  • Curricular Context:

    • Course: Fundamentals of Programming
    • Module Focus: Week 3 — Decisions and Validation
    • Author: Nasalifya Simbeye
    • Institution: Brook Besor University
  • Workbook Utilization Guidelines:

    • Material should be printed or completed directly within an exercise book.
    • Every exercise must be actively attempted before consulting solutions.
    • The official Week 3 Answers PDF is released separately by the course lecturer.
  • Tiered Learning Progression:

    • Level 1 (Basics): Designed to establish core confidence and foundational syntax familiarity.
    • Level 2 (Apply It): Structured to cultivate practical problem-solving skills and logical chaining.
    • Level 3 (Challenge): Formulated to stretch analytical reasoning through multi-conditional edge cases and validation constraints.

Foundational Concepts: Decisions and Boolean Logic

  • Conditions:

    • A condition is defined as a programmatic expression or question that evaluates strictly to a Boolean value of either True\text{True} or False\text{False}.
    • Canonical Example: \text{age} \tightge 18, which evaluates whether the value stored in the variable age\text{age} is greater than or equal to the integer 1818.
  • Boolean Data Type:

    • A fundamental binary data type named after George Boole.
    • Can hold only one of two possible states: True\text{True} or False\text{False}.
    • Serves as the operational basis for all branching decisions in digital computing.
  • Comparison Operators:

    • Dedicated symbols used to compare two operand values and yield a Boolean result:
    • ==== : Equality operator (evaluates to True\text{True} if both operands are exactly equal in value; distinct from the single assignment operator ==).
    • !=!= : Inequality operator (evaluates to True\text{True} if operands do not equal each other).
    • >> : Strictly greater than.
    • << : Strictly less than.
    • \tightge : Greater than or equal to.
    • \tightle : Less than or equal to.
  • Logical Operators:

    • Used to combine or negate Boolean expressions:
    • and\text{and} : Conjunction operator. Requires both surrounding conditions to evaluate to True\text{True} simultaneously for the entire expression to return True\text{True}. If either condition is False\text{False}, the entire statement evaluates to False\text{False}.
    • or\text{or} : Disjunction operator. Requires at least one condition to evaluate to True\text{True} for the entire expression to return True\text{True}.
    • not\text{not} : Unary negation operator. Inverts the Boolean truth value; transforms True\text{True} into False\text{False}, and False\text{False} into True\text{True}.
  • Selection Control Structures:

    • if Statement: A conditional control structure that executes an indented block of code if and only if its associated condition evaluates to True\text{True}.
    • elif Statement: Short for "else if". Sequentially introduces an alternative condition to test only when the preceding if or elif tests evaluate to False\text{False}.
    • else Statement: The default branch that executes when all prior conditions within the decision chain evaluate to False\text{False}.
  • Input Validation:

    • The programmatic practice of testing user input to ensure it meets required criteria (e.g., correct type, positive magnitude, within reasonable realistic boundaries) before processing.
    • Protects software from runtime crashes, security exploits, impossible states, and corrupted data.

Part A: Guided Practice

  • Level 1: Basics:

    • Meaning of \text{age} \tightge 18:
    • Evaluates whether the variable age\text{age} contains a numeric value of 1818 or higher.
    • Yields True\text{True} for ages such as 1818, 1919, 4040, and yields False\text{False} for ages such as 1717, 00, or −1-1.
    • Even or Odd Number Determination:
    • Evaluates parity using the modulo operator %\text{\%}, which returns the remainder of a division by 22:
      • If n \tightpmod 2 == 0, the number has no remainder and is printed as Even.
      • Otherwise (else), the remainder is non-zero and the number is printed as Odd.
  • Level 2: Applied Logic:

    • Academic Grade Categorization Program:
    • Takes a numerical grade input (mark\text{mark}) and categorizes achievement levels based on explicit thresholds:
      • Distinction: Mark of 7575 or higher (\text{mark} \tightge 75).
      • Pass: Mark between 5050 and 7474 inclusive (\text{mark} \tightge 50).
      • Fail: Any mark falling below 5050 (mark<50\text{mark} < 50).
    • Bank Account Withdrawal Condition:
    • A transaction must satisfy two simultaneous conditions:
      1. The requested withdrawal amount must be strictly positive (amount>0\text{amount} > 0).
      2. The requested withdrawal amount cannot exceed the available funds (\text{amount} \tightle \text{balance}).
    • Combined logical condition: \text{amount} > 0 \text{ and } \text{amount} \tightle \text{balance}.
  • Level 3: Challenge — Mobile Money Withdrawal Engine:

    • Business Constraints:
    • Transaction amount must be positive: amount>0\text{amount} > 0.
    • Available account funds must be sufficient: \text{amount} \tightle \text{balance}.
    • Transaction must not violate the maximum daily limit: \text{amount} \tightle 5000 (a maximum ceiling of K5,000\text{K}5{,}000 per day).
    • Programmatic Structure and Output Cases:
    • Case 1 (Invalid Non-Positive Input): \text{amount} \tightle 0 →\rightarrow Print error: "Invalid amount. Withdrawal must be greater than K0."
    • Case 2 (Daily Limit Breach): amount>5000\text{amount} > 5000 →\rightarrow Print error: "Transaction denied. Amount exceeds daily limit of K5,000."
    • Case 3 (Insufficient Balance): amount>balance\text{amount} > \text{balance} →\rightarrow Print error: "Transaction denied. Insufficient account balance."
    • Case 4 (Successful Transaction): When all validation criteria pass →\rightarrow Deduct amount from balance and print: "Withdrawal successful. Please collect your cash."

Part B: Conceptual Analysis and Explanations

  • Temperature Classification Chain:

    • Logic thresholds:
    • Hot: 30^\tightcirc\text{C} and above (\text{temperature} \tightge 30).
    • Warm: 15^\tightcirc\text{C} to 29^\tightcirc\text{C} inclusive (\text{temperature} \tightge 15 evaluated after checking for \tightge 30).
    • Cold: Below 15^\tightcirc\text{C} (else).
    • Implementation example:
    • First check: if temperature >= 30: print "Hot".
    • Second check: elif temperature >= 15: print "Warm".
    • Final branch: else: print "Cold".
  • The Flaw of Inverted Conditional Ordering in elif Chains:

    • Problem Scenario: Placing \text{mark} \tightge 50 before \text{mark} \tightge 75 in a grade classification program.
    • Mechanism of the Bug:
    • Conditional branches evaluate sequentially from top to bottom.
    • The first branch that evaluates to True\text{True} runs its block, and Python bypasses the entire remainder of the chain.
    • Because any number greater than or equal to 7575 (such as 8585 or 9595) is mathematically also greater than or equal to 5050, a high mark will satisfy \text{mark} \tightge 50 immediately.
    • As a consequence, a student scoring 9090 will receive a "Pass", and the condition \text{mark} \tightge 75 will never be reached or executed under any circumstances.
  • Compound Age Range Evaluation:

    • Checking that a person is within working-age brackets (1818 to 6565 inclusive):
    • Boundary condition lower limit: \text{age} \tightge 18.
    • Boundary condition upper limit: \text{age} \tightle 65.
    • Complete compound expression: \text{age} \tightge 18 \text{ and } \text{age} \tightle 65.

Part C: Self-Test Reference and Solutions

  • 1. Definition of "Condition":

    • Option A: The plan for solving a problem, written in plain language, before you touch any code.
    • Option B: The programming language we will learn in this course.
    • Option C (Correct): A question with a True or False answer, like age >= 18.
    • Option D: A list of exact instructions that tells a computer what to do, step by step.
  • 2. Definition of "if statement":

    • Option A: A whole number with no decimal point, e.g. 5 or 100.
    • Option B (Correct): An instruction that runs a block of code only when a condition is True.
    • Option C: The exact spelling and punctuation rules of a programming language; get this wrong, and Python won't understand you.
    • Option D: A piece of text, always written inside quotation marks, e.g. "Lusaka".
  • 3. Definition of "Boolean":

    • Option A (Correct): A value that is either True or False.
    • Option B: A piece of text, always written inside quotation marks, e.g. "Lusaka".
    • Option C: A whole number with no decimal point, e.g. 5 or 100.
    • Option D: A number with a decimal point, e.g. 5.5.
  • 4. Definition of "Comparison operator":

    • Option A: The exact spelling and punctuation rules of a programming language; get this wrong, and Python won't understand you.
    • Option B: A labelled box that holds a value your program can use and change.
    • Option C: A piece of text, always written inside quotation marks, e.g. "Lusaka".
    • Option D (Correct): A symbol like ==, >, or < used to compare two values.
  • 5. Meaning of elif:

    • A contraction of "else if". It introduces a secondary or subsequent conditional check that is evaluated solely if all previous if or elif tests in the chain evaluated to False\text{False}.
  • 6. Operational Requirements of and:

    • The logical and operator strictly requires both conditions on either side of it to be True\text{True} in order to evaluate to True\text{True} overall.
  • 7. Function of not:

    • Reverses or inverts the truth value of a condition. If an expression is True\text{True}, applying not produces False\text{False}; if it is False\text{False}, not produces True\text{True}.
  • 8. Purpose of Input Validation:

    • Input validation prevents programs from crashing, eliminates security bugs, and guarantees that anomalous, out-of-range, or impossible user inputs (e.g., negative ages, negative currency amounts, text where numbers are expected) are caught and handled gracefully.
  • 9. Meaning and Role of ==:

    • Represents the structural comparison operator for equality. It checks whether the left-hand value is equal to the right-hand value, returning True\text{True} or False\text{False} without altering either operand.

Part D: Milestone 3 Assignment — A Decision Program

  • Assignment Brief:

    • Implement a functional program that makes automated decisions utilizing real-world Zambian systems, pricing, or regulations.
  • Required Project Deliverables:

    1. Multi-Branch Logic Implementation:
    • Develop a full program utilizing if, elif, and else constructs.
    • Must model a real-world decision rule (e.g., public bus fare calculated by age bracket, retail commercial discounts based on total Kwacha purchase amount, or mobile money fees).
    1. Comprehensive Validation System:
    • Implement input checks that actively intercept impossible or absurd entries (such as negative numbers or human ages exceeding biologically plausible limits).
    1. Structured Test Table:
    • Compile a rigorous test table with a minimum of six (66) distinct test cases.
    • Must explicitly incorporate boundary value analysis (testing the exact thresholds where behavior changes, such as boundary edges 00, 1717, 1818, 6565, 7474, 7575).
  • Evaluation Rubric (Total: 20 Marks):

    • Criterion 1: Correct Decisions (55 Marks)

    • Full Marks (55): Right output generated for every logical case.

    • Partial Marks: Mostly correct, with some gaps, omissions, or algorithmic errors.

    • Little or No Marks: Missing, highly unclear, or unoriginal work.

    • Criterion 2: Validation (55 Marks)

    • Full Marks (55): Impossible input handled clearly and gracefully with informative feedback.

    • Partial Marks: Mostly correct validation, with some logical gaps or edge-case oversights.

    • Little or No Marks: Missing validation, completely unclear handling, or unoriginal work.

    • Criterion 3: Test Table (55 Marks)

    • Full Marks (55): Exactly six or more comprehensive tests recorded, explicitly including boundary cases.

    • Partial Marks: Mostly complete test table, but lacks boundary coverage or contains minor errors.

    • Little or No Marks: Test table missing, unclear, incomplete, or unoriginal work.

    • Criterion 4: Clarity (55 Marks)

    • Full Marks (55): Source code is neatly styled, consistently indented, properly commented, and confirmed to be original work.

    • Partial Marks: Readable code with minor stylistic issues, sparse comments, or formatting gaps.

    • Little or No Marks: Messy, unreadable, uncommented, or unoriginal work.

  • Pre-Submission Quality Assurance Checklist:

    • [ ] I answered every task.
    • [ ] My work is neat and easy to read.
    • [ ] I used real Zambian examples where asked.
    • [ ] I checked my spelling and numbers.
    • [ ] This is my own work.