Big picture
Python helps convert raw entries into useful results. A school club can calculate spending, classify entries and summarise a small dataset using short programs. The language is readable, but a program still needs a precise algorithm and an explicit understanding of value types.
This chapter develops a complete introductory workflow: define the problem, choose representations, write expressions, control execution and test results. The examples use fixed data so every stated output can be reproduced without guessing what a user might type.
Learning goals
Design algorithms and describe flowchart conventions.
Identify Python tokens and choose suitable types.
Compute expressions and format output.
Use selection and loops with boundary checks.
Classify errors and plan meaningful tests.
Core ideas
1. Algorithms, pseudocode and flowcharts
An algorithm specifies finite, unambiguous steps. Identify the inputs, outputs and permitted values before choosing Python statements. A club budget algorithm can multiply the number of items by their price, subtract a discount and report the payable amount. Writing these steps first exposes missing assumptions.
Pseudocode expresses the logic without strict language syntax. A flowchart represents it visually: start/end terminators, input/output parallelograms, process rectangles, decision diamonds and connecting arrows. A decision should have clearly labelled alternatives, and a repetition must show how control returns to its condition. Do not confuse a diagram of program flow with a diagram of computer hardware. Both use arrows, but they describe different things and answer different questions.
2. Python environment and tokens
Interactive mode is useful for quick experiments; a script stores a repeatable program. Do not copy prompt marks into a script. Python is case-sensitive and uses indentation to define suites. A comment begins with # outside a string and should explain intent or an assumption.
Tokens include keywords, identifiers, literals, operators and delimiters. Identifiers such as club_total may contain letters, digits and underscores, but cannot start with a digit or use a reserved keyword. Literals include 16, 4.5, 'club' and True. A quoted word is a string literal; an unquoted word is interpreted as a name or keyword. Clear names let a reader connect each expression to the original problem rather than decoding a chain of unrelated single letters.
3. Variables, types and conversion
Assignment binds a variable name to a value object. The right side is evaluated before binding. Built-in scalar types include int, float, bool and str. An integer quantity and a numeric-looking string require different operations: text concatenation is not addition.
input() returns text. Use int for an integer string and float for a decimal representation when appropriate. Conversion can fail if the text does not match the requested form. A roll number with leading zeros may need to remain text because it is an identifier rather than a quantity. Mutable collections, introduced separately, can change in place; integers and strings cannot. Rebinding an immutable value is allowed and should not be confused with altering the original object itself.
4. Arithmetic and formatted output
Arithmetic operators include +, -, , /, //, % and *. Parentheses clarify order. Exponentiation precedes multiplication and division, which precede addition and subtraction. Floor division rounds toward negative infinity, while remainder supports divisibility and digit algorithms.
items = int("9")
unit_price = 18
discount = 12
payable = items * unit_price - discount
print(payable)
print(payable / 5)
print("Payable", payable, sep=": ")Output:
150
30.0
Payable: 150Nine items cost 9 × ₹18 = ₹162; subtracting ₹12 gives ₹150. Sharing among five gives ₹30 each. Python displays the true-division result as 30.0. The sep argument changes punctuation between values, while end changes what follows the print call. An exact-output question requires both value and display formatting.
5. Comparisons and selection
Comparison operators produce Boolean results. Use == for equality and = for assignment. Logical and requires both conditions, or requires at least one, and not negates a condition. To accept a percentage from zero through one hundred, both bounds must hold.
An if–else chooses between two paths. An elif chain checks alternatives in order and runs the first matching branch. For category thresholds, order from the most restrictive high threshold downward when higher values also meet lower thresholds. Nest validation outside classification so invalid inputs are not treated as valid categories. Check the exact boundary: “at least fifty” includes fifty. A correct-looking label is insufficient if the code reaches it only through an accidental or overbroad condition.
6. Iteration and accumulator patterns
A for loop traverses an iterable. range excludes its stop and supports a nonzero step. A while loop repeats while its condition is true and requires progress toward termination. Both can execute zero times.
total = 0
for amount in [25, 40, 35]:
total += amount
print(total)
for n in range(3, 10, 3):
print(n, end=" ")
print()Output:
100
3 6 9 Initialise an accumulator before the loop. A counter records the number of qualifying records rather than their total. break exits the nearest loop; continue skips the rest of one iteration. In a while loop, continue can accidentally bypass the state update. Trace that path separately rather than assuming every line runs on every iteration.
7. Errors and testing strategy
A syntax error breaks language structure, such as a missing colon after if. A runtime error arises while executing, such as division by zero or invalid conversion. A logical error produces the wrong answer despite successful execution. Correct the cause, not just the displayed symptom.
Prepare test cases before trusting the program: a typical input, a boundary and an invalid case. For an average, an empty qualifying group requires a policy rather than division by zero. For a discount, test a purchase just below, exactly at and just above the threshold. A trace table records variable names, current values and types after relevant statements. Compare expected results with actual outputs; a successful run proves only that the program ran, not that it met the task.
8. A complete classification and calculation example
The following small program validates a fixed score, chooses a label and computes a percentage-like display. Its data are chosen so every branch decision is visible.
score = 42
maximum = 60
if 0 <= score <= maximum:
percentage = score / maximum * 100
if percentage >= 75:
label = "Distinction"
elif percentage >= 40:
label = "Pass"
else:
label = "Improve"
print(percentage, label)
else:
print("Invalid score")Output:
70.0 PassThe fraction 42 ÷ 60 equals 0.7, then multiplication by one hundred gives 70%. The score is valid, the first threshold fails and the second succeeds. Changing the input to a value above maximum should trigger validation instead of classification. This illustrates a broader principle: validation, computation and reporting are separate responsibilities even when written in one short script.
A reliable approach to questions
Read the command word before choosing an answer. A definition needs the distinguishing feature; a comparison needs matching criteria on both sides; an application needs a reason linked to the situation.
Extract the supplied evidence and assumptions. Keep a small working table rather than relying on memory. If information is absent, state the limit instead of inventing a value or claiming certainty.
Work through the relevant rule one step at a time. For a program, record the changing state; for a scenario, connect the requirement to the feature that meets it. Explain why the closest alternative fails.
Check the result against the original question, including boundary cases, units and wording. Present a concise final answer followed by enough reasoning for another student to reproduce your conclusion.
Connections that matter
Computer fundamentals explain where instructions execute.
Data collections allow the same processing to handle many records.
Data projects combine validation, cleaning and summarisation.
Common mistakes
Converting every digit string to int: identifiers may need leading zeros.
Using equality assignment interchangeably: == and = have different roles.
Counting the range stop as an item: it is excluded.
Treating a successful run as proof: compare with independent expected results.
Revision checklist
I can design algorithms and describe flowchart conventions.
I can identify Python tokens and choose suitable types.
I can compute expressions and format output.
I can use selection and loops with boundary checks.
I can classify errors and plan meaningful tests.