UTILISING PROGRAMMING LANGUAGE
Basic Programming Concepts
1. Variables: Variables are placeholders or containers in programming that hold data
values.
Meaningful Names: Choose names that reflect the variable's purpose or content.
This makes your code easier to understand.
Case Sensitivity: In Python, variable names are case-sensitive
Use Underscores for Readability: Use underscores to separate words in variable
names for better readability. This style is called snake case.
Avoid Reserved Keywords
2. Data Types: Data types define the kind of data a variable can hold
I. Primitive Data Types
int (Integer): Represents whole numbers without any decimal point. Integers are
used for counting or indexing purposes.
float (Floating Point): Represents numbers with a fractional part. char (Character):
Represents a single character. Characters are used to represent letters, digits,
punctuation marks, etc.
bool (Boolean): Represents true or false values.
II. Complex (non-primitive) Data Types
Array: A collection of elements of the same data type, accessed by an index.
List: Similar to arrays but more flexible. Lists can contain elements of different data
types and allow dynamic addition and removal of elements.
Dictionary: A collection of key-value pairs, where each key is unique. Dictionaries
are efficient for looking up values associated with unique keys. They are particularly
useful in scenarios where quick access to data is required.
3. Comments: Notes added to code to give further explanation of the code and is
ignored when being run.
Why Use Comments?
Clarity Debugging Documentation
Types
1. Single-Line Comments: These comments start with # and continue to the end of the
line.
2. Multi-Line Comments: These comments span multiple lines and are found between
””” comment”””
Functions
A function is a block of code designed to perform a specific task. It describes how to
perform the particular task.
Why Use Functions?
Reusability Organization Readability Avoid Repetition
Basic Structure of a Function
Function Definition: This is where you write the code for the function.
Function Call: This is where you use the function in your program.
Definition
def function_name(parameters):
# Code block
return value
Explanation:
def: Keyword to define a function.
function_name: Name of the function.
parameters: Variables that the function takes as input (optional).
return: Keyword to return a value from the function (optional).
Calling
To use the function, you call it with arguments:
sum = add_numbers(3, 5)
print(sum) # Output: 8
4. Arithmetic Operators
Modulus (%): Returns the remainder of a division operation
5. Comparison Operators
Equal to (==)
Not equal to (!=)
Greater than (>)
Less than (<)
Greater than or equal to (>=)
Less than or equal to (<=)
Control Structures
If Statement
Used to execute a block of code if a specified condition is true.
Example:
if temperature > 30:
print("It's hot outside!")
Explanation: If the temperature is greater than 30 degrees, the program will print "It's hot
outside!"
if-else Statement
Used when there are two possible paths: one if the condition is true, and another if the
condition is false.
Example:
if temperature > 30:
print("It's hot outside!")
else:
print("It's not that hot.")
Explanation: If the temperature is greater than 30 degrees, the program will print "It's hot
outside!" Otherwise, it will print "It's not that hot." 87
if-elif-else Statement:
Used when there are multiple conditions to check, one after another.
Example:
if temperature > 30:
print("It's hot outside!")
elif temperature > 20:
print("It's warm outside!")
else:
print("It's cold outside!")
Explanation: If the temperature is greater than 30 degrees, it prints "It's hot outside!" If it’s
not greater than 30 but greater than 20, it prints "It's warm outside!" Otherwise, it prints "It's
cold outside!"
Control Flow: Loops and Recursion
Control flow determines the order in which instructions are executed in a program. Loops
and recursion are two primary control flow mechanisms.
1. Loops
For Loop: Repeats a block of code a known number of times.
Example,
for i in range(5):
print(i)
Explanation: This loop repeats 5 times and prints numbers from 0 to 4.
While Loop: Repeats a block of code as long as a specified condition is true.
Example,
count = 0
while count < 5:
print(count)
count += 1
Explanation: This loop adds to the count variable each time it runs, it then prints numbers
from 0 to 4 and will continue as long as the count is less than 5. 88
2. Recursion
A technique where a function calls itself to solve a problem.
Example:
Factorial Calculation
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Explanation: The factorial function calls itself with n-1 until it reaches 1. The factorial of 5 is
calculated as 5 * 4 * 3 * 2 * 1.
Creating a Simple Calculator
Steps in creating a simple calculator
1. Prompt for User Input: Use the `input()` function to prompt the user to enter the first
number. Store this number in a variable
1. Enter the Operator: Prompt the user to enter an arithmetic operator (`+`, `-`, `*`, `/`).
Store this operator in a variable
[Link] for the Second Number: Again, use the `input()` function to prompt the user to
enter the second number. Store this number in a variable
1. Perform Calculation Based on Operator: Use conditional statements (`if`, `elif`, `else`)
to perform the calculation based on the operator entered by the user.
1. Display the Result: Finally, use the `print()` function to display the calculated result to the
user.
Understanding Machine Learning Concepts
Introduction to Machine Learning: Learning Like a Machine
Machine learning (ML) is a branch of artificial intelligence (AI) that allows computers to learn
from data and improve their performance over time
Real-world examples of ML
Recommendation Systems
Voice Assistant
Image Recognition
Types
Supervised Learning:
Think of a teacher guiding a student. In supervised learning, the model is trained on labelled
data, meaning each data point has a corresponding label or answer. The model learns the
relationship between the input data and the desired output, enabling it to make predictions
on new, unseen data.
Ex:
Image Classification Predicting House Prices
Unsupervised Learning:
Unsupervised learning is where the model is trained on data that has not been labelled or
categorised. The goal is to identify relationships within the data without any prior knowledge
of what the outputs should be.
Clustering
Clustering algorithms analyse the data points and calculate how similar or different they are
from each other. This similarity is often measured using distance. Data points that are close
together are considered similar and are grouped into the same cluster.
Applications of Clustering Customer Segmentation - Businesses can group customers
based on their buying behaviour, demographics, or preferences to target marketing
campaigns effectively.
Image Segmentation - Clustering can be used to identify different objects or regions within
an image.
Document Clustering - Clustering helps organise large collections of documents into groups
based on their content, making it easier to find relevant information.
Anomaly Detection - By identifying outliers that don't belong to any cluster, clustering can
help detect unusual data points that might indicate errors or fraudulent activities.
Common Clustering Algorithms
K-means Clustering - This algorithm divides data into a predefined number of clusters
Hierarchical Clustering - This algorithm creates a hierarchy of clusters, starting with
individual data points and merging them based on similarity.
Reinforcement Learning
The model learns through trial and error, interacting with an environment and receiving
rewards for desired actions and penalties for mistakes.
Environment Action
State/Observation - The current situation of the agent
Reward—The feedback from the environment
Data Collection and Preparation
Define the Problem Collect Images
Label Images Image Quality Tips
Libraries are collections of pre-written code that help developers implement machine
learning algorithms efficiently. They provide a wide range of functionalities that simplify the
process of developing, training, and deploying machine learning models.
NumPy
Think of NumPy as a tool that a mathematician might use to perform computations. It's a
Python library designed to help you work with numbers and arrays (which are like lists of
numbers). NumPy excels at performing various mathematical operations quickly and
efficiently. For instance, if you need to add up all the numbers in a large list or carry out
complex calculations, NumPy makes the process straightforward and fast.
Pandas
Pandas, on the other hand, is like an upgraded version of NumPy tailored for handling
structured data, similar to tables in Excel. While NumPy focuses on numbers and arrays,
Pandas is designed to help you organise and analyse data arranged in rows and columns. It
is built on top of NumPy, leveraging its capabilities but adding a layer of powerful data
manipulation features.
Scikit-Learn
Scikit-Learn, often referred to as Sklearn, is a powerful and easy-to-use open-source Python
library for machine learning. It provides simple and efficient tools for data mining and data
analysis, making it a valuable resource for building machine learning models.
A machine learning (ML) model is a mathematical representation that is trained on data to
make predictions or decisions without being explicitly programmed to perform the task. The
process involves feeding data to the model and allowing it to learn patterns and
relationships within the data, which it can then apply to new, unseen data.
Key Components of a Machine Learning Model
Data Algorithm
Features - The attributes or variables in the data that are used to make predictions.
Training - The process of using data to teach the model
Evaluation—Assessing the model's performance using metrics such as accuracy, precision,
recall, F1 score, or mean squared error.
Prediction
Implementing machine learning and Ethical Consideration
Ethical Considerations in Machine Learning fix any problems. For example, if a model
Models unfairly denied loans to certain groups,
developers must identify and correct the
Ethics refers to the principles that guide our issue.
decisions and actions to ensure they are
fair, just, and respectful of others. In How to Fix It
machine learning, ethics involves creating
and using models in ways that are Test models thoroughly, follow guidelines
responsible and do not harm individuals or and regulations, and have a way for people
society. to report problems.
Let us now take a look into the various Let us consider the Potential Societal
ethical considerations to take into Impacts of machine learning models
consideration when building a machine Positive Impacts
learning model and how to tackle it when
they arise 1.
107 Accurate models can help make better
decisions in many areas, like predicting the
Bias in training data happens when the data weather or diagnosing diseases.
used to teach a machine learning model
contains errors or unfair representations of 2.
certain groups.
Machines can do routine tasks faster and
How to Fix It more accurately, allowing humans to focus
on complex problems.
Use data from different sources, check for
errors, and ensure that all groups are fairly 108
represented.
Negative Impacts
Fairness means ensuring the machine
1.
learning model treats everyone equally,
regardless of background. If not designed carefully, models can worsen
existing inequalities, making life harder for
How to Fix It
disadvantaged groups.
Use fairness checks, design the model to
2.
avoid bias, and involve diverse people in the
development process. Using a lot of personal data can lead to
privacy issues, like data breaches or misuse
Privacy involves protecting people's
of information.
personal information from misuse. For
example, if a model uses student health 3.
records, it must keep that information
confidential and secure. Complex models can be hard to understand,
making it difficult to trust their decisions.
How to Fix It
Anonymize data, use techniques to ensure
privacy, and only collect necessary
information.
Accountability means that developers are
responsible for the model's actions and must
Introduction to Web Development
Web development is the process of creating websites and web applications that are
accessible through the [Link] development can range from creating a simple
static page of plain text to developing complex web-based applications, social network
services, and e-commerce platforms.
Importance of Web Development.
Accessibility Business Presence Communication Education
E-commerce
Types of Websites
a) Static Websites
Characteristics of Static Websites.
- Content does not change unless manually updated by the developer.
- Easier and faster to create and host.
- Generally cheaper to develop and maintain.
- Suitable for small websites with limited content updates, such as portfolios or
informational websites.
b) Dynamic Websites
Characteristics of Dynamic Websites.
- Content can change based on user inputs, time, or other variables.
- More interactive and engaging for users.
- Can handle large amounts of data and frequent content updates.
- Suitable for e-commerce sites, social networks, blogs, and other data-driven
applications.
Types of Databases
SQL Databases: Use structured query language (SQL) to manage data. Examples include
MySQL, PostgreSQL, and SQLite.
Relational Model: Data is organised into tables with rows and columns. Tables can be linked
using primary and foreign keys.
Queries: SQL commands to perform operations on the data
NoSQL Databases: Use various data models, such as documents, key-value pairs, or
graphs. Examples include MongoDB, CouchDB, and Redis.
Document Model: Data is stored in JSON-like documents. (Note: JSON means JavaScript
Object Notation, which is a standard text-based format for representing structured data and
is a lightweight way of storing and transferring data across the internet.)
Key-Value Pair Model: Data is stored as key-value pairs.
Graph Model: Data is stored as nodes and relationships.
Document Model: Data is stored in JSON-like documents. (Note: JSON means JavaScript
Object Notation, which is a standard text-based format for representing structured data and
is a lightweight way of storing and transferring data across the internet.)
Key-Value Pair Model: Data is stored as key-value pairs.
Graph Model: Data is stored as nodes and relationships.
Understanding Web Page Editors
Web page editors are software tools that help developers create, edit, and manage the
content and design of websites.
Purposes of Web Page Editors
Simplify Web Development Streamline Workflow
Enhance Productivity Ensure Compatibility
Types of Web Page Editors
WYSIWYG Editors:
WYSIWYG editors allow developers to create web pages visually without writing code.
These editors provide a graphical interface where users can drag and drop elements, such
as text, images, and buttons, onto a canvas.
Features
Drag-and-Drop Interface Real-Time Preview
Templates and Themes Integrated Tools
Ex
Adobe Dreamweaver WordPress Wix and Squarespace
Code Editors: Code editors are designed for developers who prefer to write their code
themselves.
Features
Syntax Highlighting Code Completion Debugging Tools
Version Control Integration: Many code editors integrate with version control systems, such
as Git, allowing developers to manage changes to their code. They also provide an audit
trail of changes and rollback features in case of any issues that arise once code has been
deployed.
Ex
Visual Studio Code Sublime Text Atom
Basic HTML and CSS
HTML, or Hypertext Markup Language, is the standard language for creating and designing
web pages. HTML is used to structure content on the web. It tells the web browser how to
display text, images, and other media. HTML elements are the building blocks of web
pages, defining everything from headings and paragraphs to links and images.
Introduction to CSS
Is a language used to describe the presentation of a web page written in HTML. CSS
controls the layout, colors, fonts, and overall appearance of web content.
Benefits of CSS
Consistency Flexibility Separation of Concerns
Multimedia Integration
Best Practices for Multimedia
Optimizing Media for the Web
Image Optimization
Choosing the Right Format
Video Optimization
Choosing the Right Format
Introduction to Responsive Design
Responsive design refers to designing and developing websites that adapt seamlessly to
various screen sizes and devices.
1. Improved User Experience: Responsive design provides a consistent and user-friendly
experience across all devices, which can lead to higher user satisfaction and engagement.
2. Increased Mobile Traffic: With the growing use of smartphones and tablets, a responsive
design ensures that your website is accessible and functional on mobile devices, potentially
increasing traffic.
3. Cost-Effective: Maintaining a single responsive website is more cost-effective than
creating and managing separate versions for different devices.
4. Search Engine Optimization (SEO) Benefits: Search engines like Google favour
responsive designs, which can improve your website’s ranking in search results. Google
recommends responsive web design as the best practice for mobile configuration.
5. Future-Proofing: Responsive design helps ensure your website remains functional and
relevant as new devices and screen sizes emerge.
Key Principles of Responsive Design
Fluid Grid Layouts Flexible Images Media Queries Responsive
Typography
Touch-Friendly Design
Web Accessibility: Web accessibility refers to making websites and web applications usable
by people with disabilities.
Perceivable: Operable Understandable Robust
Importance of Web Accessibility
Inclusivity Legal Compliance Enhanced User Experience
Broader Audience SEO Benefits
Creating a Shopping Cart
A shopping cart is an essential component of any e-commerce website. It allows users to
select products, view their selected items, and proceed to checkout.
Cart Container:
A section or div where the cart items will be displayed.
Item List:
A list showing the items added to the cart, including product details like name, quantity, and
price.
Cart Controls:
Buttons or controls for modifying item quantities, removing items, and proceeding to
checkout.
Summary:
A summary section displaying the total price and other relevant information.
Payment Gateway Integration and Shopping Cart & Checkout Process
Payment Gateways are essential components of online payment systems. They securely
transmit transaction information between a customer's and merchant's banks.
Importance
Security Convenience Efficiency Compliance
Ex
PayPal Stripe Square [Link]
1. Enhancing User Experience:
Teachers should help learners understand how user accounts allow for personalized
experiences, such as customized recommendations, order history, and saved preferences.
They also provide convenience by allowing users to store their shipping addresses, payment
methods, and other details, making future purchases faster and easier.
2. Order Tracking:
This allows customers to view past orders, track shipments, and manage returns through
their accounts. Learners should also understand that e-commerce provides real-time
updates on the status of their orders, improving transparency and customer satisfaction.
3. Customer Support:
It allows users to manage support requests, view responses, and track the progress of their
issues. Customer service representatives can access user profiles to better support and
resolve issues more efficiently.
4. Security:
User accounts offer a secure way to access personal information and transaction history.
Implementing secure login mechanisms allows authentication and reduces the risk of
unauthorized access and fraud.
Basic User Account Features
Account Creation:
Registration Forms: Users fill out registration forms with details such as name, email
address, and password. This includes email verification or CAPTCHA to ensure authenticity
and reduce spam.
CAPTCHA: Stands for Completely Automated Public Turing Test to Tell Computers and
Humans Apart, and is a challenge-response test that acts as an authentication mechanism
on websites, search engines, and web applications to ensure that users (with or without
password-based credentials) are human beings and not automated bots trying to crowd the
system and cause a cyberattack
Login:
Users enter their credentials (username/email and password) to access their accounts.
Managing User Accounts
Viewing and Editing Profile Information
Profile Management: user profiles allow individuals to view and update their personal
information, such as names, email addresses, and passwords.
Security and Trustworthiness
Protection of Sensitive Information is an essential part of e-commerce websites. The website
handles sensitive data such as customer personal details, payment information, and order
histories. Ensuring this data is protected from unauthorized access is crucial.
Confidentiality Integrity Availability
Secure Authentication Mechanisms
Password Hashing and Salting
Password Hashing:
Hashing is a process that converts a password into a fixed-size string of characters, which
appears random. It is a one-way function, meaning it cannot be reversed to obtain the
original password.
Hashing passwords ensures that even if the password data is compromised, the actual
passwords are not easily retrievable.
Password Salting:
Salting involves adding a unique, random string (the salt) to a password before hashing.
This prevents attacks where attackers guess passwords using precomputed hash tables
(rainbow tables).
Salting ensures that even if two users have the same password, their hashed passwords will
differ due to the unique salt.
Implementing Two-Factor Authentication
Two-factor authentication (2FA) adds an extra layer of security by requiring users to provide
two forms of identification: something they know (password) and something they have (a
temporary code sent to their device or email address).
Database Design
A relational database organises data into structured tables related to each other through
shared data values. This organisation is crucial for efficiently managing large volumes of
data, ensuring data integrity, and facilitating complex queries and data analysis.
Importance of a Database
Efficiently Manages Large Volumes of Data - Organizes and stores extensive data
collections in an orderly manner.
Ensures Data Integrity and Reduces Redundancy - Maintains accuracy and consistency,
preventing duplicate data entries.
Facilitates Complex Queries and Data Analysis - Supports advanced data retrieval and
analysis for better decision-making.
Dynamic and Responsive Functioning: This function handles multiple aspects of e-
commerce, such as product listings, customer details, orders, and transactions, making the
website dynamic and responsive.
Components
- Tables (Relations)
A table is a collection of related data entries consisting of columns and rows.
- Rows (Records/Tuples)
- Entities
Entities are objects or concepts about which data is stored in a database, and attributes are
the properties or details of an entity
- Attributes
Attributes are the columns in a database table that define the properties of the entities
stored in the table.
Relationships between Entities
Relationships link tables based on shared data. In a relational database, these relationships
can be:
One-to-Many - A single customer can place many orders.
Many-to-Many - Products can appear in multiple orders, and orders can contain multiple
products.
Primary Key
A primary key is a field (or a combination of fields) in a database table that uniquely
identifies each row or record within that table.
Characteristics
Uniqueness Non-null
Immutability - Ideally, the value of a primary key should not change. Once assigned, it
should remain the same for the lifetime of the record.
Importance
- Ensuring Data Integrity
- Efficient Data Retrieval
- Establishing Relationships
Foreign Key
A foreign key is a column or set of columns in one table that refers to the primary key in
another table. It creates a relationship between the two tables, allowing data from one table
to be associated with data from another.
Characteristics
Referential Integrity - Foreign keys help maintain referential integrity by ensuring that the
value in the foreign key column corresponds to a valid value in the referenced table’s
primary key column.
Null able - Foreign key columns can contain NULL (empty) values, meaning a record might
not always have a related record in the referenced table.
Consistency - The foreign key enforces consistency between the two related tables,
ensuring the data remains accurate and reliable.
Importance
- Establishing Relationships
- Maintaining Data Integrity
- Facilitating Joins - Foreign keys join tables in queries, allowing for complex data
retrieval and analysis.
Relational Database Tables and Fields
Tables and fields form the backbone of a relational database. Each table is a collection of
related data entries, and each field is a column that holds specific information about every
record in the table.
Schema Design
Schema Design is a conceptual blueprint that outlines how data is organised within a
database. It involves defining tables, fields, relationships, and constraints to ensure data
integrity and efficient access.
Query: A request for data or information from a database.
SELECT Statement
A SQL command is used to retrieve data from one or more tables. It specifies the columns
to be retrieved and the conditions for selecting records.
INSERT Statement
An SQL command is used to add new records to a table. It specifies the table and the
values for each column.
UPDATE Statement
A SQL command is used to modify existing records in a table. It specifies the table, columns
to be updated, and the conditions for updating records.
DELETE Statement
An SQL command is used to remove records from a table. It specifies the table and the
conditions for deleting records.
WHERE Clause
An SQL clause specifies conditions that filter records in a query. It is used with SELECT,
UPDATE, and DELETE statements.
ORDER BY Clause
A SQL clause is used to sort a query's results based on one or more columns. You can
specify ascending (ASC) or descending (DESC) order.
GROUP BY Clause
A SQL clause used to group rows that have the same values in specified columns into
summary rows. It is often used with aggregate functions.
e.g SELECT CategoryID, COUNT(*) AS NumberOfProducts FROM Product GROUP BY
CategoryID;
JOIN
A SQL operation combines rows from two or more tables based on a related column. Types
of joins include INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN.
e.g SELECT [Link], [Link] FROM Product INNER JOIN
Category ON [Link] = [Link]
Aggregate Functions
This function performs calculations on a set of values and returns a single value. Common
aggregate functions include COUNT(), SUM(), AVG(), MAX(), and MIN().
e.g SELECT AVG(Price) AS AveragePrice FROM Product;
Constraint
Rules applied to table columns to ensure the validity and integrity of data. Constraints
include NOT NULL, UNIQUE, CHECK, and FOREIGN KEY.
e.g CHECK (Price >= 0) ensures that the price cannot be negative.