Introduction to Problem-Solving and Python Programming
Fundamentals of Computer Science and Problem-Solving
Core Definition of Computer Science:
- Computer Science is the systematic study of problems, problem-solving methodologies, and the solutions produced by this process.
- It can be summarized fundamentally in two words: problem solving.
- Given any problem, the primary objective is to design an algorithm capable of solving it.
Nature and Characteristics of Algorithms:
- Definition: An algorithm is a step-by-step list of obvious, logical, sequential, and unambiguous instructions designed to solve a specific problem or perform a designated task.
- Real-World Metaphor: An algorithm is functionally identical to a culinary recipe for preparing a specific food dish; sequentially following the predetermined steps leads directly to the completed dish or solution.
- Essential Criteria:
- Lucid, Precise, and Unambiguous: Every step must convey a single, unmistakable action.
- Correctness: Must generate the correct solution under all possible valid test cases.
- Finiteness: Must terminate and end after a finite number of operations.
Analysis of Algorithm Quality (Case Study: Area of a Rectangle Calculator):
- Problem Formulation: Construct an algorithm to calculate the area of a rectangle where the user supplies the width and the height. Mathematical formula: .
- Solution A (Optimal / Good):
- Step 1: Ask the user to enter Width.
- Step 2: Ask the user to enter Height.
- Step 3: Set Area to .
- Step 4: Display Area for the user.
- Assessment: Correct because its sequence is logical, explicit, and sequentially orderly.
- Solution B (Defective – Lacks Explicitness):
- Step 1: Ask the user to enter Width.
- Step 2: Ask the user to enter Height.
- Step 3: Calculate Area.
- Step 4: Display Area for the user.
- Defect: Step 3 fails to define the computational formula; the instructions are not obvious or explicit.
- Solution C (Defective – Out of Sequence):
- Step 1: Set Area to .
- Step 2: Ask the user to enter Width.
- Step 3: Ask the user to enter Height.
- Step 4: Display Area for the user.
- Defect: Width and Height have not been acquired or initialized prior to Step 1. They do not exist in memory at the time of calculation.
- Solution D (Defective – Illogical Dependency on Undefined Entities):
- Step 1: Set Area to .
- Step 2: Display Area for the user.
- Defect: Operates on undefined variables that are never declared, input, or assigned anywhere in the algorithm.
- Solution E (Defective – Semantic / Logical Inaccuracy):
- Step 1: Ask the user to enter Width.
- Step 2: Ask the user to enter Height.
- Step 3: Set Area to .
- Step 4: Display Area for the user.
- Defect: Calculates an invalid mathematical result. If and , the algorithm outputs instead of the true value of .
Program Design and the Development Lifecycle
Computational Limitations of Computers:
- Computers lack independent cognitive intelligence and cannot deduce a solution spontaneously.
- The human programmer must analyze the problem, formulate precise instructions, and instruct the computer to execute them.
The Two-Phase Software Engineering Model:

- Problem-Solving Phase:
- 1. Analysis and Specification: Understand and define the exact problem domain and identify the expected behavior of the solution.
- 2. General Solution (Algorithm): Establish the necessary data structures, types, and sequence of operational steps.
- 3. Verification: Trace and manually verify the algorithm step-by-step against test scenarios to confirm correct behavior before writing code.
- Implementation Phase:
- 1. Concrete Solution (Program): Translate the verified algorithm into a syntax-compliant programming language.
- 2. Test: Execute the program on actual computational hardware and compare machine outputs against manual expectations.
- 3. Maintenance Phase: Refactor and update existing code to accommodate evolving feature requests, adapt to new operating conditions, or patch bugs uncovered in live use.
Comprehensive Seven-Step Program Development Framework:
- 1. Define the Problem: Segment requirements into Inputs, Processing Steps, and Outputs (IPO model).
- 2. Outline the Solution: Decompose the overarching problem into modular, manageable sub-problems.
- 3. Develop the Outline into an Algorithm: Expand the high-level outline into an explicit algorithmic sequence.
- 4. Test the Algorithm for Correctness: Walk through edge cases before any coding occurs to catch logic errors early.
- 5. Code the Algorithm: Implement the logic in a programming language (e.g., Python).
- 6. Run the Program: Execute using a compiler or interpreter with specialized test cases to check for syntax, runtime, and logic errors.
- 7. Document and Maintain: Add internal comments, write external documentation, and perform upkeep across the program's lifecycle.
Program Development Case Study: Simple Calculator
Functional Requirements:
- The program accepts two integer values and an arithmetic operator ().
- The program computes the correct result and displays the outcome to the user.
Technical Specifications:
- Display a startup greeting:
"Welcome to our Calculator". - Prompt the user for the first integer ().
- Prompt the user for the second integer ().
- Prompt the user to select an operator from the set ().
- Calculate the outcome and print the resulting value on screen before exiting.
- Display a startup greeting:
Algorithmic Formulation:
- Step 1: Display a welcome message that says,
"Welcome to our Calculator". - Step 2: Ask the user to enter the first number and save it to variable .
- Step 3: Ask the user to enter the second number and save it to variable .
- Step 4: Ask the user to select the sign () and save it in variable .
- Step 5: If is equal to
"+", set . - Step 6: Otherwise, set .
- Step 7: Display .
- Step 1: Display a welcome message that says,
Pseudocode Representation: ```text
- print "Welcome to our Calculator"
- X = input "Enter the first number:"
- Y = input "Enter the second number:"
- Sign = input "Select - or +"
- if Sign is equal to "+" then:
- Sum = X + Y
- else:
- Sum = X - Y
- End if
- print Sum ```
Flowchart Architecture:

Step-by-Step Algorithm Verification:
- Test Trace 1 (Addition Path):
- Step 1: Print
"Welcome to our Calculator". - Step 2: User provides .
- Step 3: User provides .
- Step 4: User provides .
- Step 5: Evaluate conditional
Sign == "+"True (Yes). - Step 6: Compute .
- Step 7: Display
30. - Test Trace 2 (Subtraction Path):
- Step 1: Print
"Welcome to our Calculator". - Step 2: User provides .
- Step 3: User provides .
- Step 4: User provides .
- Step 5: Evaluate conditional
Sign == "+"False (No). - Step 6: Compute .
- Step 7: Display
35.
Flowcharts, Pseudocode, and Problem Representation
Distinction Among Conceptual Forms:
- Algorithm: The underlying logical set of steps required to solve a problem.
- Pseudocode: A structured representation using English-like syntax that resembles programming code without adhering to strict language syntax rules.
- Flowchart: A visual, geometric representation of sequential actions and control logic within a program.
- Actual Source Code: Formal implementations in languages such as Python, C++, Java, or C.
Flowchart Elements and Standardized Symbols:
- Oval (Terminator): Signifies the starting and ending points of an execution path (
Start,End). - Parallelogram (Input/Output): Denotes data entry or output operations (e.g., input values, display messages).
- Rectangle (Process): Represents internal operations, variable assignments, and arithmetic processing (e.g., addition, subtraction, division).
- Diamond (Decision): Represents conditional branches evaluating to True or False (e.g., If/Then/Else structures).
- Flowline (Directed Arrow): Shows the direction of logical flow through the system.
- Oval (Terminator): Signifies the starting and ending points of an execution path (
Practical Value and Scalability:
- Flowcharts are less essential for programs with few lines of code, but they become critical when systems expand to hundreds of thousands or millions of lines of code.
- Flowcharts provide a clear, high-level map of control logic, preventing architectural confusion.
Problem Walkthrough: Academic Grade Determination:
- Problem Description: Calculate a student's final grade as the arithmetic mean of four scores, then report a status of
"Pass"if the average is , or"Fail"otherwise. - Algorithm:
- 1. Ask the user to enter 4 marks ().
- 2. Calculate the marks average () by summing all marks and dividing by .
- 3. If average () is greater than or equal to :
- 4. Print
"Pass". - 5. Else:
- 6. Print
"Fail". - 7. End if.
- Pseudocode:
text input Mark1, Mark2, Mark3, Mark4 Avg = (Mark1 + Mark2 + Mark3 + Mark4) / 4 if Avg >= 60: print "Pass" else: print "Fail" End if - Verification Traces:
- Test Scenario 1: Marks are .
- Condition:
- Output:
"Pass"
- Test Scenario 2: Marks are .
- Condition:
- Output:
"Fail"
- Problem Description: Calculate a student's final grade as the arithmetic mean of four scores, then report a status of
Problem Walkthrough: Length Conversion (Feet to Centimeters):
- Conversion Ratio: .
- Pseudocode:
text LFT = input "Length in feet" LCM = LFT * 30 print LCM - Test Trace:
- Input:
- Processing:
- Output:
Problem Walkthrough: Area of a Rectangle:
- Pseudocode:
text input L, W A = L * W print A
- Pseudocode:
Decision Structures and Logical Branching
The If–Then–Else Selection Mechanism:

- A logical expression (e.g., ) evaluates to either true or false.
- When the condition evaluates to true, control follows the left/true pathway.
- When the condition evaluates to false, control follows the right/false pathway.
- Structural Syntax:
text if condition then true alternative else false alternative End if
Relational Operators Reference Table:
>: Greater than<: Less than==: Equal to>=(or ) : Greater than or equal to<=(or ) : Less than or equal to!=(or ) : Not equal to
Problem Walkthrough: Determining the Largest of Two Values:
- Pseudocode:
Input VALUE1, VALUE2 if (VALUE1 > VALUE2) then MAX = VALUE1 else MAX = VALUE2 endif print "The largest value is", MAX ``` * **Verification Traces:** * *Test Trace 1:* Inputs are , . * Check: * Branch: * Output: `"The largest value is 5"` * *Test Trace 2:* Inputs are , . * Check: * Branch: * Output: `"The largest value is 80"` * **Python Implementation:**python value1 = eval(input("Enter Value 1: ")) value2 = eval(input("Enter Value 2: "))
if value1 > value2: largest = value1 else: largest = value2
print("The largest value is", largest) ```
Computer Architecture and Programming Languages
Computer System Fundamentals:
- A computer is an electronic system engineered to store, retrieve, and process digital data.
- Hardware: The physical, visible machinery and electronic components.
- Central Processing Unit (CPU): Serves as the computational brain of the system; speed is measured in megahertz () and gigahertz ().
- Memory (RAM): Volatile primary storage accessed directly by the CPU.
- Storage Devices: Non-volatile media such as magnetic disks, solid-state drives, and CDs.
- Input Devices: Peripheral equipment such as keyboards and mice.
- Output Devices: Visual and physical presentation units such as monitors and printers.
- Communication Devices: Network devices including modems and Network Interface Cards (NIC).
- Binary Foundation: Digital computers operate using binary states ( and ) because internal digital circuits have two stable physical voltage states.
- Software: Programs consisting of instructions that direct the hardware to perform tasks.
Hierarchy of Programming Languages:
- Machine Language: Low-level, primitive instructions coded directly in binary (s and s). This is the only language a CPU can execute directly, but it is tedious and prone to error for humans.
- Assembly Language: Low-level symbolic code that replaces raw binary with human-readable mnemonics; it requires an assembler to produce machine code.
- High-Level Languages: User-friendly, English-like syntax that allows programs to run across different CPU architectures with minimal changes.
Catalog of Significant High-Level Languages:
- Ada: Named in honor of Ada Lovelace; engineered for the United States Department of Defense, used in aerospace and defense operations.
- BASIC: Beginner’s All-purpose Symbolic Instruction Code; built for novices learning programming.
- C: Developed at Bell Laboratories; bridges low-level system power with high-level code structure and portability.
- C++: An object-oriented language developed as an extension of C.
- C#: Pronounced C Sharp; an enterprise hybrid language developed by Microsoft combining paradigms from Java and C++.
- COBOL: COmmon Business Oriented Language; designed for business, enterprise data, and transaction processing.
- FORTRAN: FORmula TRANslation; designed for high-performance numerical and scientific calculations.
- Java: Developed by Sun Microsystems (later acquired by Oracle); built for platform-independent network and internet application deployment.
- Pascal: Named for Blaise Pascal; a structured programming language widely used to teach clean coding practices.
- Python: A modern, high-level, interpreted scripting language built for clear syntax and rapid development.
- Visual Basic: Created by Microsoft to support rapid visual application development in Windows environments.
Source Code Translation Paradigms:
- Terminology:
- Statements: Individual directives written in a high-level programming language.
- Source Program / Source Code: The full high-level program written by the programmer.
- The Interpretation Process:

- An interpreter reads a single statement of source code, translates it into machine or virtual instructions, and executes it immediately before proceeding to the next line.
- The Compilation Process:

- A compiler parses and translates the entire source program into an executable machine-code file, which can then be run independently by an executor.
Python Overview and Environment Setup
Language Characteristics of Python:
- General Purpose: Suitable for a wide range of software tasks, from basic scripting to large-scale data systems.
- Interpreted: Python source files are interpreted and executed line by line at runtime.
- Object-Oriented: Data is modeled through objects created from classes. A class acts as a template defining attributes and methods, supporting reusable code design.
Runtime Environments and Execution Modes:
- Interactive Mode:
- Code runs directly inside the interactive Python Shell (indicated by the
>>>prompt). - Statements execute immediately when the user presses
<Enter>, making it useful for testing single commands. - Script Mode:
- Code is written into a text file saved with the
.pyfile extension. - The interpreter parses and runs the full file from top to bottom, making this the standard approach for permanent programs.
- Core Differences:
- Script mode requires creating and saving a file before execution; interactive mode outputs results immediately.
- Script mode allows structured code editing and saving; interactive sessions are ephemeral.
Integrated Development Environments (IDEs):
- An IDE combines an editor, file explorer, runtime configuration, and debugger into a single application.
- PyCharm: A dedicated Python IDE developed by JetBrains, available as a free, open-source Community Edition.
Configuring a Project in PyCharm:
- Step 1: Open PyCharm.
- Step 2: Select New Project.
- Step 3: Provide a descriptive directory path and project name (e.g.,
"My First Project"), ensure a base Python interpreter is assigned, and click Create. - Step 4: Locate the project directory hierarchy on the left panel.
- Step 5: Right-click the root project folder, choose New, then select Python File.
- Step 6: Enter the file name without extension (e.g.,
Welcome), which createsWelcome.py. - Step 7: Enter source code into the editor workspace.
- Step 8: Right-click within the editor tab and select Run 'Welcome' (or use the shortcut
Ctrl+Shift+F10). - Step 9: Review program output in the bottom console panel.
Code Examples, Tracing, and Program Anatomy
Program Demonstrations:
- Program 1: Displaying Two Messages (
Listing 1.1 Welcome.py):
# Display two messages print("Welcome to Python") print("Python is fun") ``` * *Execution Trace:* Line 1 is a comment and is skipped. Line 2 prints `"Welcome to Python"`. Line 3 prints `"Python is fun"`. * *Output:*text Welcome to Python Python is fun ```
- Program 2: Displaying Three Messages (
Listing 1.2 WelcomeWithThreeMessages.py):
# Display three messages print("Welcome to Python") print("Python is fun") print("Problem Driven") ``` * *Output:*text Welcome to Python Python is fun Problem Driven ```
- Program 3: Evaluating an Arithmetic Expression (
Listing 1.3 ComputeExpression.py): - Problem: Compute the mathematical formula:
- Implementation:
python # Compute expression print((10.5 + 2 * 3) / (45 - 3.5)) - Output:
0.39759036144578314
- Program 1: Displaying Two Messages (
Code Tracing:
- Definition: A diagnostic technique where the programmer steps through code line by line, tracking variable values and output at each step.
Structural Components of Python Syntax:
- Statements: Individual operational commands that perform an action (e.g., a
print()call). - Indentation Rules:

- Python enforces block scope using indentation rather than braces.
- Statements at the root level must begin in column 1 (no leading whitespace).
- Unintended leading spaces produce an
IndentationError. - No Terminal Punctuation: Python statements must not end with a semicolon or period; terminal punctuation causes syntax errors.
- Case Sensitivity: Identifiers and built-in functions are case-sensitive; calling
Print()instead ofprint()causes an error. - Comments:
- Single-line comments: Preceded by the
#symbol; the interpreter ignores all characters following it on that line. - Paragraph / Multi-line comments: Wrapped between triple single quotes (
''' ... '''); the interpreter skips all content inside. - Special Characters Table:
()(Parentheses): Used with functions and expression grouping.#(Pound sign): Marks the start of a single-line comment." "(Quotation marks): Encloses string literals.''' '''(Triple quotes): Encloses multi-line paragraph comments.
- Statements: Individual operational commands that perform an action (e.g., a
Check Point Exercises:
- Check Point 1 (Syntax Correction):
- Broken Code:
python # Display two messages print("Welcome to Python") print("Python is fun"). - Errors Identified: Illegal leading whitespace on line 2, and an invalid trailing period on line 3.
- Corrected Code:
python # Display two messages print("Welcome to Python") print("Python is fun") - Check Point 2 (Output Prediction):
- Given Code:
python print("3.5 * 4 / 2 - 2.5 is") print(3.5 * 4 / 2 - 2.5) - Evaluation: Line 1 outputs literal text. Line 2 calculates: .
- Output:
text 3.5 * 4 / 2 - 2.5 is 4.5
Code Style, Documentation Standards, and Error Handling
Programming Style and Documentation:
- Programming Style: Enforces visual consistency so code is easy to read, review, and maintain.
- Documentation: Explanatory text that outlines program intent, design decisions, and usage limits.
- Commenting Best Practices:
- Include a summary comment header stating the file's purpose, key features, and implementation details.
- Academic programs should include: Name, Class Section, Instructor, Date, and Description.
- Add brief inline comments before complex logic blocks; avoid redundant comments.
- Indentation and Spacing Standards:
- Use a standard 4-space indentation level for nested blocks.
- Place spaces around mathematical and logical operators (e.g., write
20 + 50rather than20+50). - Use blank lines to visually separate logical sections of a program.
Classification of Programming Errors:
- 1. Syntax Errors:
- Occur when code breaks the grammar rules of the language (e.g., misspelled keywords, missing quotes, unclosed parentheses, or bad indentation).
- Caught by the interpreter during parsing; halts execution immediately.
- Example:
print("Hello)raisesSyntaxError: EOL while scanning string literal. - 2. Runtime Errors:
- Occur during execution when the program attempts an impossible or invalid operation (e.g., dividing by zero or opening a missing file).
- Causes abnormal program termination and displays an error traceback.
- Example 1:
print(1 / 0)raisesZeroDivisionError: division by zero. - Example 2:
x = input(...); print(x + 1)raisesTypeError: can only concatenate str (not "int") to strbecauseinput()returns string data. - 3. Logic Errors:
- Occur when a program runs without crashing but produces incorrect or unintended results.
- These are the hardest errors to detect because the interpreter cannot flag them.
- Case Study: Fahrenheit to Celsius Conversion (
Listing 1.4 ShowLogicErrors.py):- Intended formula:
- Flawed code:
python print("Fahrenheit 35 is Celsius degree ") print(5 / 9 * 35 - 32) - Result: Produces
-12.555555555555554instead of the correct value1.6666666666666667because multiplication takes precedence over subtraction. - Correction: Add parentheses around the subtraction:
5 / 9 * (35 - 32).
Systematic Debugging Methodology:
- Definition: The process of isolating, identifying, and resolving bugs within software.
- Four-Step Debugging Protocol:
- 1. Reproduce the problem: Re-run the program to consistently observe the failure.
- 2. Read the error message: Examine the traceback to find the exact line number and error type.
- 3. Locate the cause: Inspect variable values near the target line (e.g., insert temporary
print()statements). - 4. Fix and re-run: Apply the correction and re-test to confirm the issue is resolved.
- Debugging Case Study (
Listing 1.5 TotalPrice.py):
price = 20 quantity = 3 total = price * quantity print("Total: $" + total) ``` * *Traceback:* `TypeError: can only concatenate str (not "int") to str` on the final line. * *Analysis:* The `+` operator cannot concatenate a string (`"Total: $"`) directly with an integer variable (`total`). * *Fix:* Cast the numeric variable using `str(total)`:python print("Total: $" + str(total)) ```
- Corrected Output:
Total: $60
Comprehensive Check Point Review:
- Check Point 3:
- Missing a closing quotation mark produces a Syntax Error.
- Attempting to read a non-existent file produces a Runtime Error.
- Computing the area when asked for the perimeter produces a Logic Error.
- Check Point 4:
- When a program halts with a
TypeError, inspect the traceback first to locate the line number and mismatched types. - If a program finishes without crashing but returns an incorrect value, it has a Logic Error; find it using manual tracing or diagnostic
print()statements. - To inspect a suspect variable midway through execution, add a temporary
print()statement directly after assignment.