Introduction to Programming

Introduction

Programming is the art of giving precise instructions to a computer. At its core, it's about problem-solving: breaking down complex tasks into simple, unambiguous steps that a machine can execute.

Learning Objectives

By the end of this reading, you will be able to:

  • Understand what programming is and why it matters
  • Explain how computers execute programs
  • Write and run your first program
  • Understand the edit-run-debug cycle
  • Recognize different programming paradigms

1. What is Programming?

Programming is the process of creating a set of instructions that tell a computer how to perform a task. These instructions are written in a programming language - a formal language with precise syntax and semantics.

Why Learn to Program?

  1. Problem Solving: Programming teaches you to break complex problems into manageable pieces
  2. Automation: Automate repetitive tasks
  3. Creation: Build applications, games, websites, tools
  4. Understanding: Comprehend how the digital world works
  5. Career: High demand for programming skills across industries

The Programming Process

Problem → Algorithm → Code → Test → Debug → Refine
   ↑                                          |
   └──────────────────────────────────────────┘
  1. Understand the problem: What are the inputs? What output do you need?
  2. Design an algorithm: A step-by-step procedure to solve the problem
  3. Write code: Translate the algorithm into a programming language
  4. Test: Run the code with various inputs
  5. Debug: Find and fix errors
  6. Refine: Improve efficiency, readability, and robustness

2. How Computers Execute Programs

From Code to Execution

Computers only understand machine code - binary instructions (0s and 1s). Programming languages are human-readable abstractions that get translated to machine code.

Two main approaches:

Compilation: Translate entire program to machine code before running

Source Code → Compiler → Machine Code → Execute
(hello.c)                  (hello.exe)

Languages: C, C++, Rust, Go

Interpretation: Translate and execute line by line

Source Code → Interpreter → Execute
(hello.py)

Languages: Python, JavaScript, Ruby

Hybrid Approaches:

  • Java compiles to bytecode, then JVM interprets/JIT compiles
  • Python compiles to bytecode (.pyc), then interprets

Memory and Execution

When a program runs:

  1. Code is loaded into memory
  2. CPU fetches instructions one at a time
  3. CPU decodes and executes each instruction
  4. Results are stored back in memory

3. Your First Program

We'll use Python for examples throughout this course - it's readable, versatile, and widely used.

Hello, World!

The traditional first program simply outputs a greeting:

print("Hello, World!")

Running it:

$ python hello.py
Hello, World!

What Happened?

  1. print is a function - a reusable piece of code
  2. "Hello, World!" is a string - text data
  3. The parentheses () contain the function's argument - what we pass to it
  4. Python executed the instruction and displayed the result

A Slightly More Complex Example

# This is a comment - ignored by Python
name = "Alice"              # Store text in a variable
age = 25                    # Store a number

print("Hello, " + name)     # Output: Hello, Alice
print("You are", age)       # Output: You are 25

Key concepts introduced:

  • Comments: Notes for humans, ignored by computer
  • Variables: Named storage locations for data
  • Strings and Numbers: Different types of data
  • String concatenation: Joining strings with +

4. The Edit-Run-Debug Cycle

Programming is iterative. You'll spend most of your time in this cycle:

1. Edit

Write or modify code in a text editor or IDE (Integrated Development Environment).

Popular choices:

  • VS Code: Free, extensible, widely used
  • PyCharm: Python-specific, powerful
  • Vim/Neovim: Terminal-based, efficient once learned
  • Simple: Any text editor works for learning

2. Run

Execute your program and observe the output.

# Python
python myprogram.py

# Compiled languages need compilation first
gcc myprogram.c -o myprogram
./myprogram

3. Debug

When something goes wrong (and it will), you need to find and fix the problem.

Types of errors:

Syntax Errors: Code violates language rules

print("Hello"    # Missing closing parenthesis
# SyntaxError: unexpected EOF while parsing

Runtime Errors: Code is valid but fails during execution

x = 10 / 0       # Division by zero
# ZeroDivisionError: division by zero

Logic Errors: Code runs but produces wrong results

# Trying to calculate average
total = 10 + 20 + 30
average = total / 2     # Bug! Should be / 3
print(average)          # Outputs 30.0, not 20.0

Debugging Strategies

  1. Read the error message: They often tell you exactly what's wrong
  2. Print debugging: Add print statements to see what's happening
  3. Rubber duck debugging: Explain your code line by line (to a rubber duck or anyone)
  4. Binary search: Comment out half the code to isolate the problem
  5. Use a debugger: Step through code line by line

5. Programming Paradigms

Different languages encourage different ways of thinking about programs.

Imperative Programming

Tell the computer how to do something, step by step.

# Sum numbers 1 to 5
total = 0
for i in range(1, 6):
    total = total + i
print(total)  # 15

Declarative Programming

Tell the computer what you want, not how to get it.

# Sum numbers 1 to 5
total = sum(range(1, 6))
print(total)  # 15
-- SQL is declarative
SELECT SUM(price) FROM products WHERE category = 'electronics'

Object-Oriented Programming (OOP)

Organize code around "objects" that contain data and behavior.

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"{self.name} says woof!")

my_dog = Dog("Rex")
my_dog.bark()  # Rex says woof!

Functional Programming

Treat computation as evaluation of mathematical functions, avoiding state changes.

# Functional style
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
# [1, 4, 9, 16, 25]

Most modern languages support multiple paradigms - you can mix approaches.


6. Thinking Like a Programmer

Breaking Down Problems

Example: Make a peanut butter and jelly sandwich

A human understands this immediately. A computer needs:

  1. Get bread from pantry
  2. Open bread bag
  3. Remove two slices
  4. Place slices on plate
  5. Get peanut butter jar
  6. Open peanut butter jar
  7. Get knife from drawer
  8. Insert knife in peanut butter
  9. Scoop peanut butter onto knife
  10. Spread peanut butter on first slice ... and so on

Abstraction

Hiding complexity behind simple interfaces.

# We don't need to know HOW print works internally
print("Hello")

# We just need to know WHAT it does
# (displays text to the screen)

Pattern Recognition

Many problems share similar solutions. Over time, you'll recognize patterns:

  • Need to process every item? → Loop
  • Need to make a decision? → Conditional
  • Need to remember something? → Variable
  • Need to reuse code? → Function

7. Setting Up Your Environment

Installing Python

Windows:

  1. Download from python.org
  2. Run installer, check "Add Python to PATH"

macOS:

# Using Homebrew
brew install python

Linux:

# Usually pre-installed, or:
sudo apt install python3  # Debian/Ubuntu

Verifying Installation

python --version    # or python3 --version
# Python 3.11.0

Your First Interactive Session

Python has an interactive mode (REPL - Read-Eval-Print-Loop):

$ python
>>> 2 + 2
4
>>> print("Hello")
Hello
>>> exit()

Creating and Running Files

  1. Create a file called hello.py:
print("Hello, World!")
  1. Run it:
python hello.py

8. Good Practices from Day One

Write Readable Code

# Bad
x=5
y=10
z=x+y

# Good
width = 5
height = 10
area = width + height  # Wait, this should be width * height for area!

Readable code helps you catch bugs!

Comment Thoughtfully

# Bad - states the obvious
x = x + 1  # Add 1 to x

# Good - explains why
x = x + 1  # Compensate for 0-based indexing

Test As You Go

Don't write 100 lines then test. Write a little, test a little.

# Test each piece
print(2 + 2)      # Verify arithmetic works
print("Hi")       # Verify strings work
name = "Alice"
print(name)       # Verify variables work

Save Often

Unsaved work can be lost. Save frequently. Use version control (Git) when you're ready.


Exercises

Basic

  1. Install Python and verify it works by running python --version

  2. Create a file greeting.py that prints your name

  3. Use Python's interactive mode to calculate:

    • 7 * 8
    • 2 ** 10 (2 to the power of 10)
    • 17 / 5 (what do you notice?)
    • 17 // 5 (integer division)

Intermediate

  1. Write a program that:

    • Stores your name in a variable
    • Stores your birth year in a variable
    • Prints a message like "Alice was born in 1990"
  2. Find and fix the errors in this code:

print("Welcome!)
name = Alice
print("Hello, " name)

Advanced

  1. Research: What's the difference between a compiler and an interpreter? What are the tradeoffs?

  2. Write a program that calculates how many seconds are in a day, week, and year.


Summary

  • Programming is giving precise instructions to computers
  • Code is written in programming languages and translated to machine code
  • The edit-run-debug cycle is fundamental to development
  • Different paradigms (imperative, OOP, functional) offer different approaches
  • Breaking problems into small steps is the core skill
  • Start simple, test often, write readable code

Next Reading

Data Types and Variables →