Learning objectives:
- Determine the logical order of actions and order of operations (2.9.1–2.9.2)
- Choose data structures and order actions for execution time and memory (2.9.3–2.9.4)
- Know naming conventions and code style (2.9.5–2.9.6)
- Judge the suitability of an algorithm (2.9.7)
Logical order of actions
Steps must happen in an order that makes sense: input the values, then validate them, then calculate, then output. Getting this wrong gives wrong answers or errors.
Order of operations
Python follows mathematical precedence: brackets, then exponentiation, then multiplication and division (including // and %), then addition and subtraction.
print(2 + 3 * 4) # 14
print((2 + 3) * 4) # 20
average = (a + b + c) / 3 # without brackets only c would be divided
Use brackets to make outputs accurate and to avoid errors.
Efficiency
Choosing data structures
- A dictionary finds an item by key quickly, without checking every item.
- An array of one data type uses memory efficiently for large amounts of numbers.
- A list is flexible but searching it means checking items one by one.
Ordering actions
- Do work once outside a loop if it does not change inside it.
- Stop early when the answer is found (for example, exit a search once the item is found).
- Filter first so later steps process less data, saving time and memory.
- Don't keep copies of data you no longer need.
Naming conventions
- Meaningful names:
total_cost, notxortc. - snake_case: words in lower case joined by underscores (
total_cost). This is the usual Python style for variables and functions. - camelCase: first word lower case, later words capitalised (
totalCost). Common in other languages such as JavaScript.
Pick one convention and use it consistently.
Code style and readability
- Naming conventions make the purpose of each item clear.
- White space: blank lines between sections and spaces around operators make code easier to scan.
- Maximum line length: keeping lines short (Python's style guide suggests 79 characters) avoids sideways scrolling and keeps logic clear.
Judging an algorithm
When asked if an algorithm is suitable, consider whether it meets the requirements, how efficiently it uses storage and execution time, whether the data structures, data types, variables and constants are appropriate, and how readable and maintainable it is.