0% found this document useful (0 votes)
7 views29 pages

Computing Basics and Problem Solving

The document provides an introduction to computing and problem-solving, defining computing as the use of technology to solve real-world problems through software and hardware. It outlines the problem-solving process, including defining, analyzing, designing, implementing, testing, and refining solutions, while distinguishing between routine and non-routine problems. Additionally, it discusses key problem-solving techniques and provides examples in Python and Java to illustrate various concepts.

Uploaded by

maimunawant
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views29 pages

Computing Basics and Problem Solving

The document provides an introduction to computing and problem-solving, defining computing as the use of technology to solve real-world problems through software and hardware. It outlines the problem-solving process, including defining, analyzing, designing, implementing, testing, and refining solutions, while distinguishing between routine and non-routine problems. Additionally, it discusses key problem-solving techniques and provides examples in Python and Java to illustrate various concepts.

Uploaded by

maimunawant
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Introduction to Computing & Problem Solving

1.1 What is Computing?

Computing is the process of using computer technology to complete a task. It involves the
design and development of software and hardware systems that solve real-world problems. It
goes beyond simply using a computer — it includes problem analysis, logic formulation,
algorithm development, and implementation using programming languages.

Definition: Computing is any goal-oriented activity requiring, benefiting from, or creating


computers. It includes designing software, developing algorithms, managing hardware systems,
and solving problems using these technologies.

1.2 The Role of Computing in Problem Solving

Problem-solving is the central purpose of computing. From automating business processes to


creating mobile apps, computing is used to:

 Process data into information


 Automate repetitive tasks
 Model and simulate real-life systems
 Provide innovative solutions to real-world problems

Example:

Problem: You want to monitor how much energy a solar panel produces in real-time.
Solution: Use a sensor connected to a microcontroller (e.g., Arduino) that logs the data and
transmits it to a computer application for analysis and visualization.

1.3 Core Concepts of Computing

Here are some of the fundamental building blocks of computing:

Concept Description
Hardware Physical components like CPU, memory, and devices
Software Programs that run on hardware to perform tasks
Data Raw facts (e.g., numbers, text) processed by software
Algorithms Step-by-step instructions to solve a problem
Programming Languages Tools like Python, C, Java used to implement solutions

1.4 What is a Problem?

A problem is a situation or condition that requires a solution. In computing, a problem typically


refers to a task or objective that needs a computational solution.
Example: “Sort a list of student scores from highest to lowest” is a simple problem.

Problems can be:

 Quantitative (e.g., Calculate average)


 Qualitative (e.g., Find best job match for a profile)

1.5 What is Problem Solving?

Problem Solving in computing is the logical process of finding a solution to a defined challenge
using computational methods. It involves:

1. Understanding the problem


2. Breaking it down into parts
3. Finding a suitable method to solve it
4. Implementing the solution
5. Testing and refining the solution

1.6 A Simple Problem-Solving Flow

Let’s take a practical example:

Example: Compute the sum of two numbers

Step-by-step logic:

1. Start the program


2. Ask the user for two numbers (input)
3. Add the numbers
4. Display the result
5. End the program

1.7 Implementation in Python and C

✅ Python Version:

# Sum of two numbers in Python


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
total = num1 + num2
print("The sum is:", total)

The Problem-Solving Process

2.1 What is a Problem-Solving Process?


A problem-solving process is a series of logical steps used to find solutions to a problem. In
computing, it involves defining the problem clearly, designing a logical solution, implementing it
in code, testing it, and refining the output as needed.

2.2 The Problem-Solving Lifecycle in Computing

The computing problem-solving process usually follows these key stages:

1. Problem Definition
2. Problem Analysis
3. Design of Solution (Algorithm, Flowchart, or Pseudocode)
4. Implementation in Code
5. Testing and Debugging
6. Refinement and Optimization

Let’s explore each step in more detail.

2.3 Step 1: Define the Problem

This is the most important step. Understand what is being asked.

Example: “Write a program that checks whether a number is even or odd.”

Here:

 Input: A number
 Process: Check if the number is divisible by 2
 Output: Display “Even” or “Odd”

2.4 Step 2: Analyze the Problem

Ask: What do I need? What constraints exist?

Use questions like:

 What are the input values?


 What operations need to be performed?
 What output format is expected?

2.5 Step 3: Design the Solution

Use logical tools like:

 Algorithm: Step-by-step method


 Flowchart: Diagrammatic representation
 Pseudocode: Structured English description
2.6 Example: Check Whether a Number is Even or Odd

Algorithm

1. Start
2. Input a number (N)
3. If N mod 2 = 0, then print “Even”
4. Else print “Odd”
5. End

Pseudocode

Start
Input N
If N % 2 == 0
Output "Even"
Else
Output "Odd"
End

Flowchart
2.7 Step 4: Implement the Solution in Code

Let’s convert our design into actual code.

Python Code:

num = int(input("Enter a number: "))

if num % 2 == 0:
print("The number is Even")
else:
print("The number is Odd")

2.8 Step 5: Test and Debug

Always test the program with:

 Positive numbers (e.g., 4 → Even)


 Negative numbers (e.g., -3 → Odd)
 Edge cases (e.g., 0 → Even)

Debug if errors occur. For instance:

 Syntax error (wrong code format)


 Logical error (wrong calculation)
 Runtime error (division by zero)

2.9 Step 6: Refine the Solution

After verifying that the code works, think:

 Can it be more efficient?


 Can I handle more inputs at once?
 Can I improve readability or add comments?

2.10 Extra Example: Find the Maximum of Three Numbers

Let’s walk through the full process again.

Problem Statement:

Write a program to find the maximum of three numbers.

Algorithm:

1. Start
2. Input three numbers A, B, C
3. If A > B and A > C, then Max = A
4. Else if B > C, then Max = B
5. Else Max = C
6. Output Max
7. End

Python Code:

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a > b and a > c:


max_val = a
elif b > c:
max_val = b
else:
max_val = c

print("The maximum is:", max_val)

Types of Problems (Routine and Non-Routine)

3.1 What Are Problem Types?

In computing and real-life situations, problems come in different forms. Some are predictable
and repetitive, while others are unique and complex. We classify problems into two main
types:

1. Routine Problems
2. Non-Routine Problems

Understanding these categories helps us apply the right strategies to solve them.

3.2 Routine Problems

Definition:

Routine problems are problems that:

 Have a known method of solution


 Can be solved using standard procedures or formulas
 Often require little creativity
 Are frequently encountered in computing or mathematics

Examples of Routine Problems:

 Calculating the average of numbers


 Checking if a number is even or odd
 Converting temperature from Celsius to Fahrenheit
 Sorting a list of names
 Finding the factorial of a number

Example 1: Calculate Average of Three Numbers (Routine)


Algorithm:

1. Input three numbers


2. Calculate average = (num1 + num2 + num3) / 3
3. Output average

PSEUDOCODE

BEGIN
// Input three numbers
DISPLAY "Enter the first number:"
INPUT num1
DISPLAY "Enter the second number:"
INPUT num2
DISPLAY "Enter the third number:"
INPUT num3

// Calculate the average


average = (num1 + num2 + num3) / 3

// Output the average


DISPLAY "The average is: ", average
END

Explanation:

1. Input three numbers: The program prompts the user to enter three numbers
(num1, num2, num3) one by one.

2. Calculate average: The average is computed by summing the three numbers and dividing the
result by 3.

3. Output average: The calculated average is then displayed to the user.

This pseudocode is clear, structured, and language-agnostic, making it easy to implement in any
programming language.

Python Code:

a = float(input("Enter first number: "))


b = float(input("Enter second number: "))
c = float(input("Enter third number: "))

average = (a + b + c) / 3
print("Average is:", average)

3.3 Non-Routine Problems

Definition:

Non-routine problems:

 Have no fixed method of solution


 Require critical thinking, creativity, and logical reasoning
 May involve multiple steps and may not always have one correct answer
 Often arise in real-world scenarios

Examples of Non-Routine Problems:

 Developing a machine learning model to predict stock prices


 Designing a hospital management system
 Building a chatbot to answer questions in local languages
 Creating a data dashboard that adapts based on user preferences

Example 2: Password Strength Checker (Non-Routine)

Problem Description:

Write a program that checks whether a password is strong based on the following rules:

 At least 8 characters
 Includes at least one uppercase letter
 Includes at least one lowercase letter
 Includes at least one digit
 Includes at least one special character

This is non-routine because:

 There is no single standard algorithm


 The rules vary and require complex logical checks

Python Code:

import re

password = input("Enter your password: ")


if (len(password) >= 8 and
[Link](r"[A-Z]", password) and
[Link](r"[a-z]", password) and
[Link](r"[0-9]", password) and
[Link](r"[@$!%*?&]", password)):
print("Strong password")
else:
print("Weak password")

💡 Python’s regular expressions make this logic easier to implement.

🔎 Can We Solve It in C?

In C, such a problem becomes more complex because:

 It doesn’t have built-in regular expressions


 You’d need to manually loop through the string and check each character

This highlights the difference in language capability when dealing with non-routine problems.

3.4 Comparison Table

Feature Routine Problems Non-Routine Problems


Solution Method Known, standard algorithm No fixed method; problem-specific
Creativity Low High
Complexity Simple to moderate Often complex
Examples Average, max, sum, sort Chatbots, simulations, real-world apps
Loops, if-else, simple
Tools Complex logic, data structures, APIs
functions

Solution Techniques for Solving Problems

4.1 What Are Problem-Solving Techniques?

Problem-solving techniques are strategies or methods that help you break down, understand,
and effectively solve problems—especially complex or unfamiliar ones. In computing, these
techniques help in developing correct, efficient, and maintainable solutions.

4.2 Key Problem-Solving Techniques in Computing


Problem-solving is a fundamental skill in computing, and programmers use various techniques to
break down complex problems into manageable solutions. Below, we explore 7 key
techniques with Python and Java examples for clarity.

1. Abstraction
2. Analogy
3. Brainstorming
4. Trial and Error
5. Hypothesis Testing
6. Reduction
7. Divide and Conquer

Each is explained with simple illustrations

4.3 1. Abstraction

Abstraction is the process of removing unnecessary details to focus only on what’s essential to
solve a problem.

💡 Think of abstraction as zooming out to focus on the bigger picture.

Example 1: Hello world (Python)

Instead of worrying about how a “print” function works internally, you just call it:

print("Hello, world!")

You don’t worry about memory addresses, buffering, etc.—you abstract that away.

Example 2: Vehicle System (Java)

abstract class Vehicle {


abstract void start();
}

class Car extends Vehicle {


void start() {
[Link]("Car starts with a key.");
}
}

class Bike extends Vehicle {


void start() {
[Link]("Bike starts with a kick.");
}
}

public class Main {


public static void main(String[] args) {
Vehicle car = new Car();
Vehicle bike = new Bike();
[Link](); // Output: "Car starts with a key."
[Link](); // Output: "Bike starts with a kick."
}
}

Explanation:

 Vehicle is an abstract class that hides implementation details.


 Car and Bike provide specific implementations of start().

4.4 2. Analogy

Definition: Solving a problem by comparing it to a similar known problem. Or solving a new


problem by relating it to a familiar one.

🔷 Example:

If you know how to sort numbers, you can apply similar logic to sort names alphabetically.

names = ["Ali", "Zainab", "Bola", "Emeka"]


[Link]()
print(names)

Output

['Ali', 'Bola', 'Emeka', 'Zainab']

Java

import [Link];
import [Link];

public class SortNames {


public static void main(String[] args) {
List<String> names = [Link]("Ali", "Zainab", "Bola", "Emeka");
[Link](null);
[Link](names);
}
}

output:

[Ali, Bola, Emeka, Zainab]

4.5 4. Trial and Error

Testing multiple solutions until the correct one is found. You try multiple possible solutions and
keep testing until one works.

🔷 Example: Finding Prime Numbers

1. What is a Prime Number?

o A number greater than 1 that has no divisors other than 1 and itself.
o Examples: 2, 3, 5, 7, 11, 13...
2. How the Program Works

o Checks if the number is ≤ 1 → not prime.


o Checks divisibility from 2 up to √n (optimization to reduce checks).
o If any division has no remainder, the number is not prime.
o If no divisors found → prime.
3. Why Check Only Up to √n?

o If a number n is not prime, it must have a factor ≤ √n.


o Example: For n = 16 (√16 = 4), we check 2, 3, 4 → 2 divides 16 → not prime.

Python Version of the program

# Program to check if a number is prime


# A prime number is only divisible by 1 and itself

def is_prime(n):
# 1 and numbers less than 1 are not prime
if n <= 1:
return False

# Check for divisors from 2 up to square root of n


for i in range(2, int(n**0.5) + 1):
# If n is divisible by any number, it's not prime
if n % i == 0:
return False

# If no divisors found, it's prime


return True

# Test the function with some numbers


print(is_prime(5)) # Output: True (5 is prime)
print(is_prime(4)) # Output: False (4 is not prime)
print(is_prime(13)) # Output: True (13 is prime)

Java Version

public class PrimeChecker {

// Function to check if a number is prime


static boolean isPrime(int n) {
// 1 and numbers less than 1 are not prime
if (n <= 1) {
return false;
}

// Check for divisors from 2 up to square root of n


for (int i = 2; i <= [Link](n); i++) {
// If n is divisible by any number, it's not prime
if (n % i == 0) {
return false;
}
}

// If no divisors found, it's prime


return true;
}

public static void main(String[] args) {


// Test the function with some numbers
[Link](isPrime(5)); // Output: true (5 is prime)
[Link](isPrime(4)); // Output: false (4 is not prime)
[Link](isPrime(13)); // Output: true (13 is prime)
}
}

Output Examples

Outpu
Input Reason
t

5 True Only divisible by 1 and 5

4 False Divisible by 2

1 False Primes must be > 1

13 True No divisors except 1 and 13

4.7 5. Hypothesis Testing

Definition: Making educated guesses and validating them. You form a logical guess
(hypothesis), test it, and improve based on feedback.

Used in debugging or data analysis frequently.

Example: You guess that a loop fails because the index is going out of bounds: #

Hypothesis: List index is out of range

 List or array indexes start at 0


 Accessing an index that doesn’t exist causes an error
 Use len(list) in Python or [Link] in Java to avoid going out of bounds

Python Version

# We have a list with 3 items


lst = [10, 20, 30]

# Let's try to print each item in the list using a loop


# But if we use range(4), it means 0, 1, 2, 3 (4 numbers)
# Our list only has indexes 0, 1, and 2 — index 3 does NOT exist
# This will cause an "IndexError"

# ❌ Wrong version - causes error


# for i in range(4):
# print(lst[i]) # This will crash when i = 3

# ✅ Correct version - safe and works fine


# We use len(lst) which gives the length of the list (which is 3)
# So range(3) gives 0, 1, 2 — perfect!

for i in range(len(lst)):
print(lst[i]) # This prints 10, 20, 30 correctly

Java Version

public class Main {


public static void main(String[] args) {
// We have an array with 3 elements
int[] lst = {10, 20, 30};

// Let's try to print each element using a loop

// ❌ Wrong version - this causes an error


// for (int i = 0; i < 4; i++) {
// [Link](lst[i]); // Crashes when i = 3
// }

// ✅ Correct version - this works fine


// [Link] gives the size of the array (3)
// So i goes from 0 to 2, which is safe
for (int i = 0; i < [Link]; i++) {
[Link](lst[i]); // Prints 10, 20, 30
}
}
}

4.8 6. Reduction

Definition: Transforming a problem into a simpler one. This means breaking a complex problem
into simpler sub-problems.

Example: Writing a full calculator:

 Sub-problem 1: Add two numbers


 Sub-problem 2: Subtract
 Sub-problem 3: Multiply
 Sub-problem 4: Divide (handle divide by zero)

Handle one at a time.

 How to break a big problem (calculator) into smaller parts


 Use of basic operators: +, -, *, /
 The importance of checking for divide-by-zero

PYTHON VERSION

# --- SIMPLE CALCULATOR IN PYTHON ---

# 🧮 Sub-problem 1: Add two numbers


# Let's define two numbers
num1 = 10
num2 = 5

# Add them
sum_result = num1 + num2

# Print the result


print("Addition:", sum_result) # Output: 15

# ➖ Sub-problem 2: Subtract
# Subtract second number from the first
sub_result = num1 - num2

# Print the result


print("Subtraction:", sub_result) # Output: 5

# ✖️Sub-problem 3: Multiply
# Multiply the two numbers
mul_result = num1 * num2

# Print the result


print("Multiplication:", mul_result) # Output: 50

# ➗ Sub-problem 4: Divide
# Make sure we don't divide by zero
if num2 != 0:
div_result = num1 / num2 # Divide first number by second
print("Division:", div_result) # Output: 2.0
else:
print("Cannot divide by zero!")
✅ JAVA VERSION

public class Calculator {


public static void main(String[] args) {
// --- SIMPLE CALCULATOR IN JAVA ---

// Let's define two numbers


int num1 = 10;
int num2 = 5;

// 🧮 Sub-problem 1: Addition
int sum = num1 + num2;
[Link]("Addition: " + sum); // Output: 15

// ➖ Sub-problem 2: Subtraction
int subtract = num1 - num2;
[Link]("Subtraction: " + subtract); // Output: 5

// ✖️Sub-problem 3: Multiplication
int multiply = num1 * num2;
[Link]("Multiplication: " + multiply); // Output: 50

// ➗ Sub-problem 4: Division
// We must check if num2 is not zero to avoid error
if (num2 != 0) {
double divide = (double) num1 / num2; // Convert to double for decimal answer
[Link]("Division: " + divide); // Output: 2.0
} else {
[Link]("Cannot divide by zero!");
}
}
}

4.15 13. Divide and Conquer

Definition: Split the problem into smaller parts, solve each part, and combine them.

Popular in algorithms (e.g., Merge Sort, Binary Search).

Example: Recursive Factorial in Python

The factorial of a number is the product of all positive whole numbers from 1 to that number.

For example:
5! = 5 × 4 × 3 × 2 × 1 = 120

 Recursion: a function can call itself


 A base case is needed to stop the recursion
 Recursive functions can make code shorter and elegant

Python Version

# --- RECURSIVE FUNCTION TO CALCULATE FACTORIAL ---

# This function finds the factorial of a number using recursion


# Recursion means a function calls itself

def factorial(n):
# Base case: if n is 1, the factorial is 1
if n == 1:
return 1

# Recursive case: multiply n by factorial of (n-1)


return n * factorial(n - 1)

# Let's call the function with input 5


print(factorial(5)) # Output: 120

🔍 How it works step-by-step:

 factorial(5) → 5 * factorial(4)
 factorial(4) → 4 * factorial(3)
 factorial(3) → 3 * factorial(2)
 factorial(2) → 2 * factorial(1)
 factorial(1) → returns 1 (base case)
 Then all the calls multiply back:
→2*1=2
→3*2=6
→ 4 * 6 = 24
→ 5 * 24 = 120

Java Version (With Comments)

public class FactorialExample {

// This method uses recursion to calculate factorial


public static int factorial(int n) {
// Base case: if n is 1, return 1
if (n == 1) {
return 1;
}

// Recursive case: multiply n by factorial of (n - 1)


return n * factorial(n - 1);
}

public static void main(String[] args) {


// Call the method with input 5
[Link](factorial(5)); // Output: 120
}
}

Each call solves a smaller part of the problem.

Problem-solving in computing is more than just coding. Choosing the right techniques helps
you:

 Solve problems faster


 Write better code
 Build scalable solutions

Algorithms

5.1 What is an Algorithm?

An algorithm is a step-by-step procedure used to solve a specific problem.

In computing, algorithms help define:

 What should be done (logic)


 How it should be done (steps)
 When it should stop (termination)

5.2 Why Are Algorithms Important?

 They allow problems to be solved logically and systematically


 They provide the blueprint before coding
 They help improve efficiency and clarity

5.3 Properties of a Good Algorithm

To be considered valid, an algorithm must satisfy the following properties:


Property Description
Finiteness The algorithm must terminate after a finite number of steps
Definiteness Each step must be precise, clear, and unambiguous
Input Accepts zero or more inputs
Output Produces at least one output
Effectiveness Each step must be basic enough to be done manually or by a machine

5.4 Example: Algorithm to Find the Sum of Two Numbers

🔷 Step-by-Step Algorithm

1. Start
2. Read number A
3. Read number B
4. Sum = A + B
5. Display Sum
6. End

Representing Algorithms

Algorithms can be represented in various forms:

1. Plain English steps (natural language)


2. Pseudocode
3. Flowcharts
4. Code (Python, C, etc.)

We will now use pseudocode and programming examples to show how algorithms are
implemented.

Example 1: Maximum of Two Numbers

Pseudocode

Start
Input A
Input B
If A > B
Display A is maximum
Else
Display B is maximum
End

Python Code
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

if a > b:
print("Maximum is:", a)
else:
print("Maximum is:", b)

Example 2: Algorithm to Check Prime Number

🔶 Algorithm Steps

1. Start
2. Input number N
3. If N < 2, Not Prime
4. Loop from 2 to N-1
o If N divisible by any, then Not Prime
5. Else Prime
6. End

Python Code

n = int(input("Enter a number: "))

if n < 2:
print("Not Prime")
else:
is_prime = True
for i in range(2, n):
if n % i == 0:
is_prime = False
break
if is_prime:
print("Prime")
else:
print("Not Prime")

Characteristics of Efficient Algorithms

A good algorithm isn’t just correct—it should also be:

 Time-efficient (less execution time)


 Space-efficient (uses less memory)
 Scalable (works for large input sizes)
Example 3: Calculate Factorial (N!)

Algorithm

1. Start
2. Input N
3. Set result = 1
4. For i = 1 to N
o result = result * i
5. Output result
6. End

Python Code

n = int(input("Enter a number: "))


result = 1

for i in range(1, n + 1):


result *= i

print("Factorial is:", result)

Solution Formulation and Design

6.1 What Is Solution Formulation?

Solution formulation is the process of:

 Planning how a problem will be solved


 Designing the logical steps before writing code
 Representing these steps in a clear visual or written form

We commonly use:

 Flowcharts
 Pseudocode etc.

6.3 Flowcharts

🔹 What is a Flowchart?

A flowchart is a graphical representation of the sequence of operations in an information system


or program. It also be a diagram that represents the flow of a process using symbols and
arrows.

Common Flowchart Symbols


✅ Example: Draw a flowchart to convert the length in feet to centimeter.
This shows how the program takes input (Length in ft (LFT)), processes it, and gives output
(Length in cm (LCM)).

Pseudocode

What is Pseudocode?

Pseudocode is a plain-English description of the steps in an algorithm. It:

 Resembles programming structure


 Is not written in any specific language syntax
 Focuses on logic, not implementation

Example: Pseudocode to Check Even or Odd

Start
Input Number
If Number mod 2 = 0
Print "Even"
Else
Print "Odd"
End

Implementation, Evaluation, and Refinement

7.1 What Is Implementation?

Implementation is the stage where the planned solution (algorithm, flowchart, pseudocode) is
translated into an actual program using a programming language such as C, Java or Python.

7.2 Key Activities in Implementation

 Writing the code based on the algorithm or pseudocode


 Using correct syntax for the chosen programming language
 Testing the code to check correctness
 Debugging errors (syntax or logic)

Example: Implementation of Area of a Circle

Problem: Given the radius of a circle, compute the area using the formula:

Area=π×r2, ({Area} = pi times r^2)

Pseudocode:

Start
Input radius
Area = 3.14 * radius * radius
Print Area
End

Python Code:

radius = float(input("Enter radius: "))


area = 3.14 * radius * radius
print("Area of the circle is:", area)

7.3 What Is Evaluation?

Evaluation is the process of checking:

 Does the program solve the problem correctly?


 Is the solution efficient?
 Is the code readable and maintainable?
Example: Evaluating a Simple Grade Checker

Python Program:

score = int(input("Enter your score: "))

if score >= 70:


print("Grade: A")
elif score >= 50:
print("Grade: B")
else:
print("Grade: Fail")

Test Cases:

Input Expected Output


80 Grade: A
55 Grade: B
30 Grade: Fail
-10 Needs validation

❗ Evaluation reveals a flaw: Negative input should be handled.

✅ Improved Python Code:

score = int(input("Enter your score: "))

if score < 0 or score > 100:


print("Invalid score!")
elif score >= 70:
print("Grade: A")
elif score >= 50:
print("Grade: B")
else:
print("Grade: Fail")

7.4 What Is Refinement?

Refinement is the process of improving a solution by:

 Optimizing code for performance


 Adding better input validation
 Removing redundancy
 Making the code more user-friendly
Example: Refining a Simple Login Script

Initial Python Code:

username = input("Enter username: ")


password = input("Enter password: ")

if username == "admin" and password == "1234":


print("Access granted")
else:
print("Access denied")

🔶 Issues:

 Hardcoded credentials
 No option to retry
 Not secure

Refined Version with Retry and Input Checks:

attempts = 0
while attempts < 3:
username = input("Enter username: ")
password = input("Enter password: ")

if username == "admin" and password == "1234":


print("Access granted")
break
else:
print("Invalid credentials. Try again.")
attempts += 1

if attempts == 3:
print("Account locked. Too many attempts.")

7.5 Best Practices in Implementation and Evaluation

Practice Description
Use meaningful names e.g., totalScore, isPrime
Comment your code Explain important sections
Test incrementally Test small parts before combining
Handle user input properly Validate user data
Refactor when needed Clean and improve code after testing
7.6 Common Errors During Implementation

Type Description Example


Syntax Error Mistakes in the code structure Missing colon in if statement
Runtime Error Errors that occur while the program is running Dividing by zero
Logic Error The program runs, but gives wrong result Using * instead of + in calculation

You might also like