Procedural Programming (OCR A-Level Computer Science): Revision Notes
Procedural Programming
Overview
Procedural Programming is a programming paradigm based on structured, sequential steps called procedures or functions. It organises code into a series of instructions that are executed in order. Procedural programming languages, like Python, VB.NET, and C, are ideal for tasks with a clear, step-by-step flow. This approach emphasises variables, constants, selection, iteration, subroutines, and more, which we'll explore below.
Variables and Constants
Variables are named storage locations that hold values which can change during programme execution.
For example:
score = 100 # Variable score is assigned the value 100
Constants are named storage locations that hold values which remain the same throughout the programme. In Python, constants are typically written in uppercase to signal that they shouldn't change:
Example:
PI = 3.14159 # Constant PI represents the value of pi
Sequence
In procedural programming, code is executed line-by-line in the order it is written, known as sequence. This linear execution ensures that steps are followed systematically.
Selection (Conditional Statements)
Selection allows the programme to choose between different paths based on conditions. This is usually implemented with if-else statements.
Example in Python:
age = 18
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Iteration (Loops)
Iteration enables repeating a block of code multiple times until a certain condition is met, often using for and while loops.
Example using a for loop:
for i in range(5):
print("Iteration:", i)
Subroutines (Functions and Procedures)
Subroutines are blocks of code that perform specific tasks and can be reused throughout the programme. Subroutines in procedural languages are usually created as functions.
Functions: These are subroutines that return a value.
Example:
def add(a, b):
return a + b
Procedures: These perform a task but do not return a value. In Python, a procedure is a function without a return statement.
Using subroutines improves code readability and modularity by breaking down complex tasks into smaller, manageable parts.
String Handling
String handling allows manipulation of text-based data, such as combining, slicing, or searching within strings.
Example:
text = "Hello, World!"
print(text.lower()) # Outputs: hello, world!
print(text[0:5]) # Outputs: Hello
File Handling
File handling is the ability to read from and write to external files, which is crucial for persistent data storage.
Example of reading from and writing to a file:
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, file!")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content) # Outputs: Hello, file!
Boolean and Arithmetic Operators
Boolean Operators: and, or, not – used to form logical expressions.
Example:
is_raining = True
is_cold = False
print(is_raining and is_cold) # Outputs: False
Arithmetic Operators: +, -, *, /, // (integer division), % (modulus), ** (exponentiation) – used for mathematical calculations.
Example:
result = (10 + 5) * 2 # Outputs: 30
Example Code: Simple Banking Application
Example: Below is a Python example of a simple procedural programme that simulates basic banking actions, such as checking a balance and making a deposit or withdrawal.
# Define constants and variables
balance = 1000.00 # Initial balance
# Function to display the balance
def check_balance():
print("Your current balance is:", balance)
# Function to deposit an amount
def deposit(amount):
global balance
balance += amount
print(f"Deposited ${amount}. New balance is: ${balance}")
# Function to withdraw an amount
def withdraw(amount):
global balance
if amount > balance:
print("Insufficient funds!")
else:
balance -= amount
print(f"Withdrew ${amount}. New balance is: ${balance}")
# Main programme loop
while True:
print("\\n--- Banking Menu ---")
print("1. Check Balance")
print("2. Deposit")
print("3. Withdraw")
print("4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
check_balance()
elif choice == 2:
deposit_amount = float(input("Enter amount to deposit: "))
deposit(deposit_amount)
elif choice == 3:
withdraw_amount = float(input("Enter amount to withdraw: "))
withdraw(withdraw_amount)
elif choice == 4:
print("Exiting programme.")
break
else:
print("Invalid choice. Please try again.")
Explanation of the Example:
- Variables: balance is used to store the current bank balance.
- Functions: Separate functions (check_balance, deposit, withdraw) are used to handle different banking actions.
- Selection: The if-elif-else statements allow the user to select from different menu options.
- Iteration: The while loop keeps the programme running until the user decides to exit.
Note Summary
Common Mistakes in Procedural Programming
- Forgetting to Use global: In Python, to modify a global variable within a function, you must declare it as global.
- Infinite Loops: If the condition in a loop is not correctly updated, it can create an infinite loop, causing the programme to run indefinitely.
- Poorly Structured Code: Mixing variables and functions without clear organisation can make the code difficult to read and maintain.
Key Takeaways
- Procedural Programming organises code into sequences of statements that are executed in order.
- Key features include variables, constants, selection, iteration, subroutines, string handling, file handling, and Boolean/arithmetic operators.
- Modularisation: Functions and procedures make the code modular, allowing reuse and simplifying complex tasks.
- Debugging Skills: Procedural programming develops skills for tracing and debugging code due to its linear nature.