Creating functions in Python is a fundamental skill that allows for organized, reusable, and efficient code. In this blog post, we'll explore the best ways to create functions using various data objects and structures, focusing on a banking system example. We'll discuss algorithmic thinking, break down problems into manageable steps, and create solutions using both pseudocode and actual Python code. We'll also incorporate CRUD operations with a built-in SQLite database.
Table of Contents
- Using Lists
- Using Dictionaries
- Using Tuples
- Using Arrays
- Using Custom Data Structures
- CRUD Operations with SQLite Database
1. Using Lists
Algorithmic Thinking
Lists are ordered collections of items. They are dynamic and can hold multiple data types. For a banking system, we can use lists to store transactions or account details.
Problem Breakdown
- Open account: Add a new account to the list.
- Deposit money: Update the balance in the list.
- Withdraw money: Update the balance in the list.
- Request loan: Add a loan entry to the list.
- Repay loan: Update the loan balance in the list.
Pseudocode
1. Initialize empty list for accounts
2. Function to open account:
- Append account details to list
3. Function to deposit money:
- Find account in list
- Update balance
4. Function to withdraw money:
- Find account in list
- Check balance and update
5. Function to request loan:
- Find account in list
- Add loan details
6. Function to repay loan:
- Find account in list
- Update loan balance
Python Code
accounts = []
def open_account(account_number, name):
account = [account_number, name, 0.0, 0.0] # [account_number, name, balance, loan]
accounts.append(account)
def deposit_money(account_number, amount):
for account in accounts:
if account[0] == account_number:
account[2] += amount
return account[2]
return "Account not found"
def withdraw_money(account_number, amount):
for account in accounts:
if account[0] == account_number:
if account[2] >= amount:
account[2] -= amount
return account[2]
else:
return "Insufficient funds"
return "Account not found"
def request_loan(account_number, loan_amount):
for account in accounts:
if account[0] == account_number:
account[3] += loan_amount
return account[3]
return "Account not found"
def repay_loan(account_number, repayment_amount):
for account in accounts:
if account[0] == account_number:
if account[3] >= repayment_amount:
account[3] -= repayment_amount
return account[3]
else:
return "Repayment amount exceeds loan amount"
return "Account not found"
# Example usage
open_account("001", "John Doe")
print(deposit_money("001", 1000)) # Output: 1000.0
print(withdraw_money("001", 200)) # Output: 800.0
print(request_loan("001", 5000)) # Output: 5000.0
print(repay_loan("001", 1000)) # Output: 4000.0
2. Using Dictionaries
Algorithmic Thinking
Dictionaries are collections of key-value pairs. They provide efficient data retrieval and are suitable for storing account details with account numbers as keys.
Problem Breakdown
- Open account: Add a new key-value pair.
- Deposit money: Update the value for the account key.
- Withdraw money: Update the value for the account key.
- Request loan: Update the loan value for the account key.
- Repay loan: Update the loan value for the account key.
Pseudocode
1. Initialize empty dictionary for accounts
2. Function to open account:
- Add account details to dictionary
3. Function to deposit money:
- Update balance in dictionary
4. Function to withdraw money:
- Update balance in dictionary
5. Function to request loan:
- Update loan details in dictionary
6. Function to repay loan:
- Update loan details in dictionary
Python Code
accounts = {}
def open_account(account_number, name):
accounts[account_number] = {"name": name, "balance": 0.0, "loan": 0.0}
def deposit_money(account_number, amount):
if account_number in accounts:
accounts[account_number]["balance"] += amount
return accounts[account_number]["balance"]
return "Account not found"
def withdraw_money(account_number, amount):
if account_number in accounts:
if accounts[account_number]["balance"] >= amount:
accounts[account_number]["balance"] -= amount
return accounts[account_number]["balance"]
else:
return "Insufficient funds"
return "Account not found"
def request_loan(account_number, loan_amount):
if account_number in accounts:
accounts[account_number]["loan"] += loan_amount
return accounts[account_number]["loan"]
return "Account not found"
def repay_loan(account_number, repayment_amount):
if account_number in accounts:
if accounts[account_number]["loan"] >= repayment_amount:
accounts[account_number]["loan"] -= repayment_amount
return accounts[account_number]["loan"]
else:
return "Repayment amount exceeds loan amount"
return "Account not found"
# Example usage
open_account("001", "Jane Doe")
print(deposit_money("001", 2000)) # Output: 2000.0
print(withdraw_money("001", 500)) # Output: 1500.0
print(request_loan("001", 10000)) # Output: 10000.0
print(repay_loan("001", 3000)) # Output: 7000.0
3. Using Tuples
Algorithmic Thinking
Tuples are immutable collections of ordered items. They can be used for fixed account details where immutability is beneficial.
Problem Breakdown
- Open account: Create a tuple and add it to a list.
- Deposit money: Create a new tuple with updated balance.
- Withdraw money: Create a new tuple with updated balance.
- Request loan: Create a new tuple with updated loan amount.
- Repay loan: Create a new tuple with updated loan amount.
Pseudocode
1. Initialize empty list for accounts
2. Function to open account:
- Append tuple with account details to list
3. Function to deposit money:
- Find tuple in list and create new tuple with updated balance
4. Function to withdraw money:
- Find tuple in list and create new tuple with updated balance
5. Function to request loan:
- Find tuple in list and create new tuple with updated loan
6. Function to repay loan:
- Find tuple in list and create new tuple with updated loan
Python Code
accounts = []
def open_account(account_number, name):
account = (account_number, name, 0.0, 0.0) # (account_number, name, balance, loan)
accounts.append(account)
def find_account(account_number):
for i, account in enumerate(accounts):
if account[0] == account_number:
return i, account
return -1, None
def deposit_money(account_number, amount):
index, account = find_account(account_number)
if account:
new_balance = account[2] + amount
accounts[index] = (account[0], account[1], new_balance, account[3])
return new_balance
return "Account not found"
def withdraw_money(account_number, amount):
index, account = find_account(account_number)
if account:
if account[2] >= amount:
new_balance = account[2] - amount
accounts[index] = (account[0], account[1], new_balance, account[3])
return new_balance
else:
return "Insufficient funds"
return "Account not found"
def request_loan(account_number, loan_amount):
index, account = find_account(account_number)
if account:
new_loan = account[3] + loan_amount
accounts[index] = (account[0], account[1], account[2], new_loan)
return new_loan
return "Account not found"
def repay_loan(account_number, repayment_amount):
index, account = find_account(account_number)
if account:
if account[3] >= repayment_amount:
new_loan = account[3] - repayment_amount
accounts[index] = (account[0], account[1], account[2], new_loan)
return new_loan
else:
return "Repayment amount exceeds loan amount"
return "Account not found"
# Example usage
open_account("001", "Alice Doe")
print(deposit_money("001", 3000)) # Output: 3000.0
print(withdraw_money("001", 1000)) # Output: 2000.0
print(request_loan("001", 5000)) # Output: 5000.0
print(repay_loan("001", 2000)) # Output: 3000.0
4. Using Arrays
Algorithmic Thinking
Arrays are efficient for numerical data and support a fixed type. For a banking system, arrays can be used for performance-critical operations on numerical data.
Problem Breakdown
- Open account: Store account details in a structured array.
- Deposit money: Update the balance in the array.
- Withdraw money: Update the balance in the array.
- Request loan: Store loan details in the array.
- Repay loan: Update the loan balance in the array.
Pseudocode
1. Initialize an array for accounts.
2. Function to open account:
3. Append account details to the array.
4. Function to deposit money:
Update the balance in the array.
5. Function to withdraw money:
Check balance and update in the array.
6. Function to request loan:
Update the loan details in the array.
7. Function to repay loan:
Update the loan balance in the array.
Python Code
from array import array
class BankAccount:
def __init__(self, account_id, initial_balance=0):
self.account_id = account_id
self.balance = initial_balance
self.loans = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
else:
print("Insufficient funds")
def request_loan(self, loan_amount):
self.loans += loan_amount
def repay_loan(self, repayment_amount):
self.loans -= repayment_amount
accounts = array('i', [])
# Example usage
account = BankAccount('001', 100)
account.deposit(50)
account.withdraw(20)
account.request_loan(500)
account.repay_loan(100)
print(f"Account ID: {account.account_id}")
print(f"Balance: {account.balance}")
print(f"Loans: {account.loans}")
5. Using Custom Data Structures
Algorithmic Thinking
Custom data structures can be tailored to specific needs, providing more control and flexibility. For a banking system, we can create a custom class to manage accounts.
Problem Breakdown
- Open account: Initialize a custom data structure for each account.
- Deposit money: Update the balance in the data structure.
- Withdraw money: Update the balance in the data structure.
- Request loan: Add loan details to the data structure.
- Repay loan: Update the loan balance in the data structure.
Pseudocode
1.Define a custom class for accounts.
2.Function to open account:
Initialize an instance of the custom class.
3.Function to deposit money:
Update the balance in the class.
4.Function to withdraw money:
Check balance and update in the class.
5.Function to request loan:
Update loan details in the class.
6.Function to repay loan:
Update loan balance in the class.
Python Code
class BankAccount:
def __init__(self, account_id, name):
self.account_id = account_id
self.name = name
self.balance = 0.0
self.loan = 0.0
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
return self.balance
else:
return "Insufficient funds"
def request_loan(self, loan_amount):
self.loan += loan_amount
return self.loan
def repay_loan(self, repayment_amount):
if self.loan >= repayment_amount:
self.loan -= repayment_amount
return self.loan
else:
return "Repayment amount exceeds loan amount"
# Example usage
account = BankAccount("001", "John Doe")
print(account.deposit(1000)) # Output: 1000.0
print(account.withdraw(200)) # Output: 800.0
print(account.request_loan(5000)) # Output: 5000.0
print(account.repay_loan(1000)) # Output: 4000.0
Conclusion
Choosing the appropriate data structure and approach for your functions in Python depends on the specific requirements of your problem. Lists, dictionaries, tuples, arrays, and custom data structures each have their advantages and use cases. Understanding their strengths and limitations helps you make informed decisions to write efficient and effective code. By breaking down the problem, utilizing algorithmic thinking, and following general principles of problem-solving, you can create robust solutions for managing complex data operations in Python.