Programming Fundamentals

Programming Fundamentals introduces beginners to the essential concepts of computer programming and problem-solving. This structured course covers algorithms, pseudocode, Python programming, variables, data types, operators, loops, functions and data structures through practical examples and exercises. Learn how software works, understand programming logic and develop the skills needed to write, test and improve your own programs.

How to study: type every example yourself, predict the output before running it, change one input, and keep a notebook of errors. The goal is not to memorise syntax; it is to explain why a program works.

Programming Fundamentals: Course Map and Prerequisites

No advanced prerequisite is required. Comfort with arithmetic, a text editor and a willingness to practise are enough. Modules 1–13 build the programming model, 14–20 develop data representation and object design, 21–27 build reliability and performance intuition, and 28–32 connect the foundations to data structures, version control and problem solving. Use the Python for Data Science guide when you want a data-focused next step.

1–4. Software, algorithms, compilers and paradigms

1. What programming is and how software works

Analogy: a recipe tells a cook what to do; a program tells a processor what to do. Software is a collection of instructions and data. The operating system loads a program, gives it memory and other resources, and the processor executes low-level instructions. Your Python source is text; the Python runtime parses it, creates objects and performs operations.

Example:

message = "Hello, CampusCareer"
print(message)

The first line binds a name to a string object. The second asks Python to send that value to standard output. Expected output is Hello, CampusCareer. Change the value, predict the result and run it. Common errors are spelling a name differently, using a value before assigning it and assuming output is automatically saved to a file.

Exercise: describe the input, processing and output of a marks calculator. Solution: input is marks, processing is sum and division, and output is the average and perhaps a grade. Interview: what happens between running a source file and seeing output?

2. Algorithms, pseudocode and flowcharts

Analogy: an algorithm is a travel route with decisions and steps. It is a finite, unambiguous method for solving a class of problems. Pseudocode expresses logic without language syntax; a flowchart represents start, action, decision and end with standard shapes.

START
READ marks
IF marks >= 40
    PRINT "Pass"
ELSE
    PRINT "Try again"
END

Python expresses the same algorithm with indentation. First identify inputs and output, then write the simplest correct steps, test normal and edge cases, and only then optimise. Exercise: write pseudocode for finding the larger of two numbers. Solution: read A and B; if A > B print A; otherwise print B. Interview: how do you prove an algorithm is correct?

3. Compilers versus interpreters

Analogy: a compiler translates an entire book before printing it; an interpreter reads and acts on instructions as needed. A compiler commonly translates source to machine code or an intermediate form before execution. An interpreter executes through a runtime, often with a parse or bytecode stage. Modern systems can combine techniques, so “compiled versus interpreted” is a useful model, not an absolute division.

Python source is parsed and commonly compiled to bytecode, then executed by the Python virtual machine. This explains why syntax errors are found before a program can run and why a runtime error may occur only when a particular line is reached. Exercise: classify a syntax error and a division-by-zero error. Solution: the first prevents valid parsing; the second occurs during execution. Interview: why can an interpreted language still have a compilation step?

4. Programming languages and paradigms

Analogy: languages are different toolkits; paradigms are different ways of organising the work. Imperative programming describes steps and state changes. Object-oriented programming groups state and behaviour. Functional programming emphasises transformations and avoiding unwanted mutation. Declarative languages describe the result, as SQL does, while the system chooses execution details.

Python supports procedural, object-oriented and functional styles. Choose the simplest style that makes the problem clear. A data transformation may be clearer as a pure function; a bank account with protected state may benefit from a class. Exercise: describe a to-do list imperatively and declaratively. Interview: when is composition preferable to inheritance?

5. Variables, constants and data types

Analogy: a variable is a labelled box; a constant is a label whose value your design promises not to change. In Python, names refer to objects rather than fixed memory boxes. Common types include int, float, bool, str, list, tuple, set, dict and None.

student_count = 42
PI = 3.14159
name = "Asha"
active = True
print(type(student_count).__name__, name, active)

Python infers types at runtime. The uppercase name is a convention for a module-level constant, not an enforced restriction. Use type or isinstance when checking input. Common errors include mixing a string and a number, confusing None with zero and relying on implicit conversion. Exercise: store a student’s name and three marks, then calculate the average. Solution: use numeric values for marks and divide their sum by three. Interview: explain mutable versus immutable objects.

6. Operators and expressions

Analogy: operators are verbs in a sentence. Arithmetic operators calculate, comparison operators produce booleans, logical operators combine conditions, assignment binds results, and membership or identity operators answer different questions.

hours = 6
completed = hours >= 5 and hours <= 8
print(completed)
print(10 % 3, 2 ** 3)

Python evaluates the comparison before assigning completed; % gives a remainder and ** raises a power. Use parentheses when precedence is not obvious. Do not use is to compare ordinary values; use ==. Exercise: decide whether a number is positive and even. Solution: number > 0 and number % 2 == 0. Interview: what is short-circuit evaluation?

7. Input and output

Analogy: input is a form received by a program; output is the receipt it produces. input() returns text, even when the user types digits, so convert and validate it.

raw_age = input("Age: ")
try:
    age = int(raw_age)
    print(f"Next year you will be {age + 1}.")
except ValueError:
    print("Please enter a whole number.")

The input is read, converted, formatted into an f-string and printed. Invalid text takes the error branch. Never trust input: handle empty text, unexpected ranges and malicious content. Exercise: ask for a percentage and reject values outside 0–100. Solution: convert inside a try block, then check the range. Interview: why is validation part of program design?

8. Conditional logic

Analogy: a traffic signal selects a route based on a condition. An if runs a block when its expression is true; elif tests alternatives and else is the fallback.

score = 76
if score >= 90:
    grade = "A"
elif score >= 60:
    grade = "B"
else:
    grade = "C"
print(grade)

Conditions are tested from top to bottom, so order matters. The output is B. Avoid deeply nested conditions by using guard clauses or small functions. Exercise: classify temperature as cold, mild or hot with documented boundaries. Solution: write the boundary table before the conditions. Interview: how would you test every branch?

9–10. Loops and nested loops

9. Loops

Analogy: a loop repeats a classroom attendance check. A for loop visits items; a while loop repeats while a condition remains true.

total = 0
for mark in [70, 80, 90]:
    total += mark
print(total)

Python assigns each list element to mark, updates total, then prints 240. Use break to stop and continue to skip, but do not use them to hide confusing logic. A while loop must make progress toward termination. Exercise: sum numbers until the user enters zero. Solution: read, test zero, add otherwise, and repeat. Interview: how can an infinite loop happen?

10. Nested loops

Analogy: checking every seat in every row uses one loop for rows and one for seats. Nested loops are useful for grids, but cost grows as both dimensions grow.

for row in range(2):
    for column in range(3):
        print(row, column)

The outer loop selects 0 then 1; the inner loop visits columns 0, 1 and 2 for each row, producing six pairs. Exercise: print a 3×3 multiplication grid. Solution: nest loops from 1 through 3 and print row * column. Interview: what is the complexity of two loops over n items?

11–13. Functions, modules, parameters and scope

11. Functions and modular programming

Analogy: a function is a reusable machine with an input slot and an output slot. Modular programming divides a large program into focused files and functions.

def percentage(part, whole):
    if whole == 0:
        raise ValueError("whole cannot be zero")
    return part / whole * 100

print(percentage(3, 4))

The definition records the function, the guard rejects an invalid denominator, and return sends 75.0 to the caller. A good function has one responsibility and a name that describes it. Exercise: write a function that returns the larger of two values. Solution: compare them and return the larger. Interview: what makes a function easy to test?

12. Parameters, arguments and return values

Analogy: a parameter is the blank on a form; an argument is the value supplied on a particular form. Positional, keyword, default and variable-length arguments are available in Python.

def greet(name, prefix="Hello"):
    return f"{prefix}, {name}!"

print(greet("Ravi"))
print(greet(name="Mei", prefix="Welcome"))

The first call uses the default prefix; the second uses keywords. Prefer returning a value to printing inside a reusable function. Exercise: create a function with a default tax rate. Interview: what is the difference between a parameter and an argument?

13. Scope and lifetime

Analogy: a local variable is a note inside one room; a global variable is a notice visible across rooms. Local names are created when a function runs and normally disappear when it returns. Module-level names live while the module is loaded.

rate = 0.18
def total_with_tax(amount):
    tax = amount * rate
    return amount + tax
print(total_with_tax(100))

amount and tax are local; rate is read from the enclosing module. Prefer passing dependencies as parameters instead of changing globals. Exercise: refactor a function that reads a global discount. Solution: accept discount as a parameter. Interview: explain LEGB lookup and why global state makes tests harder.

14. Arrays and strings

Analogy: an array is a row of numbered lockers; a string is a row of characters. Python lists are dynamic sequences, while NumPy arrays provide typed numerical operations. Indexing starts at zero and slicing excludes the end index.

word = "CampusCareer"
print(word[0], word[0:7], word[::-1])

The output is C Campus C followed by the reversed string; slicing creates a new sequence. Strings are immutable, so transformations return new strings. Use join for combining many pieces. Exercise: count vowels without using a library counter. Solution: loop through lowercase characters and increment when the character is in "aeiou". Interview: why can repeated string concatenation be inefficient?

15. Searching and sorting basics

Analogy: linear search checks every book; binary search repeatedly halves a sorted shelf. Sorting arranges items according to a comparison rule.

def binary_search(values, target):
    low, high = 0, len(values) - 1
    while low <= high:
        middle = (low + high) // 2
        if values[middle] == target:
            return middle
        if values[middle] < target:
            low = middle + 1
        else:
            high = middle - 1
    return -1

print(binary_search([2, 4, 7, 9], 7))

The search returns index 2. It works only because the list is sorted; each comparison discards half the remaining range. Python’s sorted uses a stable, highly optimised algorithm; learn the reasoning even when you use a library. Exercise: implement linear search and compare its checks with binary search. Interview: what precondition does binary search require?

16. Recursion

Analogy: opening a nested set of boxes means solving one box and asking the same question about the smaller box. A recursive function calls itself with a smaller problem and must have a base case.

def factorial(n):
    if n < 0:
        raise ValueError("n must be non-negative")
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(4))

The base case returns 1; otherwise the call reduces n until it reaches zero, then returns 24 while unwinding. Missing base cases cause infinite recursion; repeated overlapping work can be slow. Exercise: recursively sum a list. Solution: empty list returns zero; otherwise return first item plus the sum of the remainder. Interview: when is iteration clearer than recursion?

17–20. Object-oriented programming

17. OOP and 18. Classes, objects and constructors

Analogy: a class is a blueprint for a student card; an object is one completed card. A constructor initialises an object when it is created.

class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def average(self):
        return sum(self.marks) / len(self.marks)

student = Student("Asha", [70, 80, 90])
print(student.name, student.average())

__init__ stores instance state, self identifies the current object, and the method calculates its average. Expected output is Asha 80.0. Use a class when state and related operations belong together; do not create classes merely to wrap every function.

19. Encapsulation, inheritance and polymorphism

Analogy: encapsulation is a vending machine exposing buttons but hiding its mechanism. Inheritance expresses an “is-a” relationship; polymorphism lets different objects respond to the same operation.

class Shape:
    def area(self):
        raise NotImplementedError

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width, self.height = width, height
    def area(self):
        return self.width * self.height

for shape in [Rectangle(3, 4)]:
    print(shape.area())

The loop calls the common interface while the subclass supplies its implementation. Keep invariants inside methods and prefer composition when inheritance creates fragile hierarchies. Interview: explain “is-a” versus “has-a”.

20. Abstraction and interfaces

Analogy: a wall socket is an interface; appliances can use it without knowing the wiring. An abstraction exposes the operations a caller needs and hides implementation detail. Python uses protocols, abstract base classes and duck typing rather than requiring one universal interface keyword.

Exercise: define a Notifier interface with a send method and provide console and email-like implementations. Solution: both classes implement the same method; the caller depends on the method, not the concrete class. Interview: why does abstraction reduce coupling?

21 and 31. Error handling, debugging and testing

Analogy: an error message is a fire alarm: investigate its location and cause instead of disconnecting the alarm. Syntax errors prevent parsing; runtime exceptions occur during execution; logic errors produce the wrong answer.

def safe_average(values):
    if not values:
        raise ValueError("values cannot be empty")
    return sum(values) / len(values)

assert safe_average([2, 4]) == 3

The function states its invalid input policy and the assertion checks a known result. Debugging means reproducing the issue, reading the traceback, inspecting values and types, reducing the case, changing one thing and adding a regression test. Catch narrow exceptions and never use a broad silent except. Unit tests check small behaviours; integration tests check components together. Exercise: add tests for an empty list, one value and negative values. Interview: why should tests include edge cases?

22. File handling

Analogy: opening a file is borrowing a book; a context manager returns it even when an error occurs. Use with, explicit encoding and a suitable mode.

from pathlib import Path

path = Path("notes.txt")
path.write_text("practicenreviewn", encoding="utf-8")
with path.open(encoding="utf-8") as file:
    lines = [line.strip() for line in file]
print(lines)

The program writes two lines, opens the file, removes line endings and prints a list. Validate paths, handle missing files deliberately and never treat untrusted file content as code. For CSV or JSON use the standard library or a documented data library. Exercise: count non-empty lines. Solution: read lines, strip whitespace and count those that remain. Interview: why is a context manager safer?

23–25. Memory, stack, heap, pointers and references

Analogy: memory is a desk; the stack is a neat pile of active call notes and the heap is a larger storage area for objects. This is a conceptual model: implementation details vary by language and runtime. Function calls create frames containing local bindings; objects such as lists live in managed memory.

a = [1, 2]
b = a
b.append(3)
print(a)

Both names reference the same list, so output is [1, 2, 3]. b = a does not copy the list. Use b = a.copy() for a shallow copy when appropriate. A reference is a way to reach an object; a pointer in languages such as C stores an address and can be manipulated explicitly. Python hides pointer arithmetic and manages memory, but aliasing and object lifetime still matter. Exercise: predict the result of modifying a nested list after a shallow copy. Interview: explain stack versus heap without claiming that every runtime implements them identically.

26–27. Time, space complexity and Big-O

Analogy: complexity predicts how a delivery route grows when the number of parcels grows. Big-O describes an upper growth trend while ignoring constants and smaller terms. A single loop over n items is usually O(n); nested independent loops are often O(n²); binary search is O(log n).

def contains_duplicate(values):
    seen = set()
    for value in values:
        if value in seen:
            return True
        seen.add(value)
    return False

The set lookup is average O(1), so time is O(n) and additional space is O(n). A nested comparison approach may use O(1) extra space but O(n²) time. Complexity depends on the operation and data structure; state assumptions and distinguish worst, average and best cases. Exercise: analyse a loop that repeatedly halves n. Solution: O(log n). Interview: why can an O(n) algorithm be faster than an O(log n) one for small inputs?

28. Basic data structures

Analogy: a list is a numbered shelf, a stack is a pile of plates, a queue is a line, a set is a bag of unique tokens, a dictionary is a labelled filing cabinet, and a tree is an organisation chart.

Structure Use Python
List/array Ordered indexed values values = [1, 2]
Stack Last in, first out stack.append(x); stack.pop()
Queue First in, first out collections.deque
Set Unique membership seen = set()
Dictionary Key-value lookup scores["Asha"]
Tree/graph Hierarchy or relationships custom nodes and adjacency lists

Choose by required operations, not popularity. A dictionary is useful for counting; a queue is useful for breadth-first processing; a stack supports undo or depth-first traversal. Exercise: count word frequencies with a dictionary. Solution: loop through words and increment counts[word] = counts.get(word, 0) + 1. Interview: compare a list membership check with a set membership check.

29. Git and version control fundamentals

Analogy: Git is a save-history system with named checkpoints and parallel drafts. A repository stores project history; a commit records a coherent change; a branch isolates work; a pull request asks others to review it.

git init
git add app.py
git commit -m "Add marks average function"
git switch -c improve-validation
git diff

Stage only intended files, write messages that explain purpose, and inspect diffs before committing. A GitHub README should state the problem, setup, usage, data source, tests and limitations. Never commit passwords, tokens, private data or virtual environments. Exercise: create a branch, make one change, inspect the diff and merge it. Interview: what is the difference between a commit and a branch?

30. Clean, readable and maintainable code

Analogy: clean code is a well-labelled workshop: another person can find tools and understand the process. Use meaningful names, short focused functions, consistent formatting, comments for why rather than what, and documentation for public behaviour.

def calculate_average(scores):
    """Return the average of a non-empty sequence of scores."""
    if not scores:
        raise ValueError("scores cannot be empty")
    return sum(scores) / len(scores)

The name, docstring and guard communicate the contract. Avoid magic numbers, duplicated logic, deeply nested conditions and premature abstraction. Refactor after tests protect behaviour. Exercise: rename unclear variables and split a 50-line function into responsibilities. Interview: how do you improve code without changing its behaviour?

32. Problem-solving techniques and a 30-exercise path

Analogy: solving a programming problem is like repairing a machine: understand the symptom, isolate the part, make a small fix and test it. Use this repeatable method: clarify inputs and outputs, write examples, identify constraints, solve a simple case, choose a data structure, state an invariant, implement, test edge cases, analyse complexity and explain trade-offs.

Level Exercises Expected progression
Beginner 1–10 Variables, conditions, loops and strings
Foundation 11–20 Functions, lists, dictionaries, searching and sorting
Intermediate 21–30 Recursion, stacks, queues, trees, complexity and design

Beginner exercises 1–10

  1. Print a greeting. Solution: call print with a string.
  2. Convert Celsius to Fahrenheit. Solution: use celsius * 9 / 5 + 32.
  3. Calculate the average of three marks. Solution: sum and divide by three.
  4. Check whether a number is even. Solution: test remainder equal to zero.
  5. Classify a score into a grade. Solution: order descending threshold conditions.
  6. Print numbers from 1 to n. Solution: use range(1, n + 1).
  7. Sum only positive numbers in a list. Solution: loop and add when value is positive.
  8. Count vowels in a string. Solution: lower the string and test membership in a vowel set.
  9. Reverse a string. Solution: use a loop or slice text[::-1].
  10. Find the largest of three values. Solution: maintain a current maximum or use comparisons.

Foundation exercises 11–20

  1. Write a reusable tax function. Solution: accept amount and rate, return the computed total.
  2. Remove duplicates while preserving order. Solution: track a seen set and append unseen values.
  3. Count word frequencies. Solution: increment dictionary values with get.
  4. Find the first repeated value. Solution: return when a value is already in a set.
  5. Implement linear search. Solution: compare each item and return its index.
  6. Implement binary search. Solution: maintain low and high bounds on sorted input.
  7. Sort records by score. Solution: use sorted(records, key=lambda row: row["score"]).
  8. Merge two sorted lists. Solution: compare front elements and advance the chosen index.
  9. Validate balanced parentheses with a stack. Solution: push opening symbols and match each closing symbol.
  10. Read a file and count non-empty lines. Solution: use a context manager and count stripped lines.

Intermediate exercises 21–30

  1. Implement factorial recursively and iteratively. Solution: compare base cases and complexity.
  2. Generate Fibonacci values efficiently. Solution: use two rolling variables instead of repeated recursion.
  3. Build a queue with deque. Solution: append on the right and remove from the left.
  4. Implement a stack-based undo list. Solution: push actions and pop to undo.
  5. Traverse a tree depth-first. Solution: visit node, then recursively visit children.
  6. Traverse a graph breadth-first. Solution: use a queue and a visited set.
  7. Find the intersection of two lists. Solution: convert one to a set and preserve the required output order.
  8. Detect whether a list has a pair summing to a target. Solution: store complements or use a two-pointer sorted approach.
  9. Design a student record class with validation. Solution: protect invariants in the constructor or setters and test invalid marks.
  10. Refactor a slow nested-loop solution. Solution: identify repeated lookup and replace it with a dictionary or set, then measure.

For each exercise, submit the problem statement, examples, code, tests, complexity analysis and a short reflection. After completing the path, build a command-line study tracker or CSV analysis tool using functions, files, tests and Git.

FAQs and references

Should I learn data structures before functions?

No. Functions and control flow are the tools used to implement and test data structures. Learn the foundations first, then study structures through small problems.

Is Python the only language worth learning?

No. Python is approachable and useful for automation and Data Science. The concepts transfer to Java, C++, JavaScript and other languages; learn a second language when a course, role or project requires it.

Which official resources should I use?

Next step: complete exercises 1–10, then use the Python for Data Science guide or the SQL interview guide. Keep your solutions in a Git repository with tests and a README so your learning becomes portfolio evidence.