Good programming practice

Validate input before processing

All inputs to a program should be validated for correctness before they are used in further processing to prevent runtime or logic errors.

def input_age():
    while True:
        try:
            age = int(input("Enter your age: "))
            if age < 0:
                print("Please enter a positive number.")
            else:
                return age
        except ValueError:
            print("That's not a valid number. Please try again.")

def main():
    age = input_age()

A clear and uncluttered mainline

The “mainline” is the main control flow of the program. Keeping the mainline clear and concise improves readability and maintainability.

def main():
initialize_program()
run_program()
clean_up()

if __name__ == “__main__”:
main()

One logical task per subroutine

A subroutine in this course is any function NOT main().

Each subroutine should perform only one logical task. This makes code easier to understand, test, and reuse.

Use of Stubs

Stubs are placeholder implementations of functions that are used during development. They allow developers to simulate parts of the functionality that have not yet been implemented.

def fetch_user_data(): # TODO: Implement data fetching logic
    pass # Stub

Appropriate use of control structures and data structures

Selecting the most suitable control structures (e.g., loops, conditionals) and data structures (e.g., lists, dictionaries) for the task at hand, contributes to clearer and more efficient code.

Writing for subsequent maintenance

Write code considering that someone else (or you in the future) will need to understand and maintain it. This includes clear naming, ample documentation, and avoiding complexity.

# Well-documented function with a clear purpose and definition
def calculate_bmi(weight_kg, height_m):
"""
Calculate and return the Body Mass Index (BMI).
Parameters:
  weight_kg (float): The weight in kilograms.
  height_m (float): The height in meters.
Returns:
  float: The calculated BMI.
"""
    return weight_kg / (height_m ** 2)

Version Control

Using version control systems like Github or inbuilt versioning in online IDEs (such as replit) to manage changes to source code over time. This is crucial for collaboration and tracking the alterations of code so mistakes can be rolled back if necessary.

Regular backup

Regularly back up the code to prevent loss of work due to hardware failure, data corruption, or other unforeseen events. This can be part of utilising online repositories or separate backup systems.

Recognition of relevant social and ethical issues

Be aware of and adhere to ethical guidelines and social implications related to programming tasks, such as data privacy, security, and accessibility. These typically fall under legal issues, which is covered elsewhere.

Exception handling

Properly catch and handle exceptions to avoid crashes and provide meaningful error messages to users or logs.

try:
    # Code that may raise an exception
    result = some_operation()
except SomeException as e:
    # Handling of the exception
    handle_error(e)

Functions are able to return a single data structure or value

While Python allows for multiple values to be returned by a function, this course frowns upon this, so do not use it. A function must only return a single entity, such as a single value or a data structure, for simplicity and clarity. A data structure such as a list or dictionary, which can contain many values, can be returned.