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
or. - Canonical Example:
\text{age} \tightge 18, which evaluates whether the value stored in the variableis greater than or equal to the integer.
- A condition is defined as a programmatic expression or question that evaluates strictly to a Boolean value of either
Boolean Data Type:
- A fundamental binary data type named after George Boole.
- Can hold only one of two possible states:
or. - 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 toif both operands are exactly equal in value; distinct from the single assignment operator).: Inequality operator (evaluates toif 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:
: Conjunction operator. Requires both surrounding conditions to evaluate tosimultaneously for the entire expression to return. If either condition is, the entire statement evaluates to.: Disjunction operator. Requires at least one condition to evaluate tofor the entire expression to return.: Unary negation operator. Inverts the Boolean truth value; transformsinto, andinto.
Selection Control Structures:
ifStatement: A conditional control structure that executes an indented block of code if and only if its associated condition evaluates to.elifStatement: Short for "else if". Sequentially introduces an alternative condition to test only when the precedingiforeliftests evaluate to.elseStatement: The default branch that executes when all prior conditions within the decision chain evaluate to.
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
contains a numeric value ofor higher. - Yields
for ages such as,,, and yieldsfor ages such as,, or . - Even or Odd Number Determination:
- Evaluates parity using the modulo operator
, which returns the remainder of a division by:- If
n \tightpmod 2 == 0, the number has no remainder and is printed asEven. - Otherwise (
else), the remainder is non-zero and the number is printed asOdd.
- If
- Meaning of
Level 2: Applied Logic:
- Academic Grade Categorization Program:
- Takes a numerical grade input (
) and categorizes achievement levels based on explicit thresholds:- Distinction: Mark of
or higher (\text{mark} \tightge 75). - Pass: Mark between
andinclusive (\text{mark} \tightge 50). - Fail: Any mark falling below
().
- Distinction: Mark of
- Bank Account Withdrawal Condition:
- A transaction must satisfy two simultaneous conditions:
- The requested withdrawal amount must be strictly positive (
). - The requested withdrawal amount cannot exceed the available funds (
\text{amount} \tightle \text{balance}).
- The requested withdrawal amount must be strictly positive (
- 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:
. - 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 ofper day). - Programmatic Structure and Output Cases:
- Case 1 (Invalid Non-Positive Input):
\text{amount} \tightle 0Print error: "Invalid amount. Withdrawal must be greater than K0." - Case 2 (Daily Limit Breach):
Print error: "Transaction denied. Amount exceeds daily limit of K5,000." - Case 3 (Insufficient Balance):
Print error: "Transaction denied. Insufficient account balance." - Case 4 (Successful Transaction): When all validation criteria pass
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}to29^\tightcirc\text{C}inclusive (\text{temperature} \tightge 15evaluated 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
elifChains:- Problem Scenario: Placing
\text{mark} \tightge 50before\text{mark} \tightge 75in a grade classification program. - Mechanism of the Bug:
- Conditional branches evaluate sequentially from top to bottom.
- The first branch that evaluates to
runs its block, and Python bypasses the entire remainder of the chain. - Because any number greater than or equal to
(such asor) is mathematically also greater than or equal to, a high mark will satisfy\text{mark} \tightge 50immediately. - As a consequence, a student scoring
will receive a"Pass", and the condition\text{mark} \tightge 75will never be reached or executed under any circumstances.
- Problem Scenario: Placing
Compound Age Range Evaluation:
- Checking that a person is within working-age brackets (
toinclusive): - 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.
- Checking that a person is within working-age brackets (
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
iforeliftests in the chain evaluated to.
- A contraction of "else if". It introduces a secondary or subsequent conditional check that is evaluated solely if all previous
6. Operational Requirements of
and:- The logical
andoperator strictly requires both conditions on either side of it to bein order to evaluate tooverall.
- The logical
7. Function of
not:- Reverses or inverts the truth value of a condition. If an expression is
, applyingnotproduces; if it is,notproduces.
- Reverses or inverts the truth value of a condition. If an expression is
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
orwithout altering either operand.
- Represents the structural comparison operator for equality. It checks whether the left-hand value is equal to the right-hand value, returning
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:
- Multi-Branch Logic Implementation:
- Develop a full program utilizing
if,elif, andelseconstructs. - 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).
- Comprehensive Validation System:
- Implement input checks that actively intercept impossible or absurd entries (such as negative numbers or human ages exceeding biologically plausible limits).
- Structured Test Table:
- Compile a rigorous test table with a minimum of six (
) distinct test cases. - Must explicitly incorporate boundary value analysis (testing the exact thresholds where behavior changes, such as boundary edges
,,,,,).
Evaluation Rubric (Total: 20 Marks):
Criterion 1: Correct Decisions ( Marks)
Full Marks (): 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 ( Marks)
Full Marks (): 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 ( Marks)
Full Marks (): 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 ( Marks)
Full Marks (): 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.