What programming languages are, why they exist, how source code becomes execution, and how to read and reason about programs
Chapter 5 introduced algorithms — the precise, step-by-step procedures that describe how to solve problems. This chapter takes the next step: explaining how those procedures are expressed in a form that a computer can actually execute. That form is called a programming language, and the text you write in one is called source code.
By the end of this chapter, you should understand why programming languages exist, how they are structured, what happens when source code is translated into a running program, what kinds of errors appear in code and why, and why readable code matters as much as correct code. These ideas carry through every programming chapter that follows.
Computers operate on streams of binary ones and zeros. Human programmers think in variables, conditions, loops, and logic. How does a programmer's intention become a running program? The answer to that question is what this chapter explains.
Computers do not think in English. They do not understand requests written in plain prose or instructions the way a person would. At the lowest level, a computer processes streams of binary signals — long sequences of ones and zeros that represent electrical states inside circuits. Everything a computer does ultimately reduces to operations on those binary signals.
This creates an obvious problem. People do not think in ones and zeros. People think in words, concepts, relationships, conditions, steps, and intentions. There is an enormous gap between how humans naturally express instructions and how computers actually process them. Programming languages exist to bridge that gap.
A programming language is a precisely defined formal language that allows humans to express instructions in a way that can be understood, checked, and executed by a computer. Programming languages are not like natural languages such as English or Spanish. Natural languages are rich, flexible, ambiguous, and context-dependent. Programming languages are designed intentionally, with exact rules that leave no room for ambiguity.
To understand why programming languages exist, it helps to think in terms of levels — a progression from instructions the CPU understands directly up to instructions that resemble human thought.
Hundreds of programming languages exist, each designed with particular goals, audiences, and tradeoffs. Some prioritize simplicity and readability — Python is often cited as an example, common in teaching, data science, and rapid development. Some prioritize raw performance — C and C++ allow precise control of memory and processor behavior, at the cost of greater complexity, and are used for operating systems and game engines. Some are domain-specific: SQL for databases, HTML for web page structure, R for statistics. Some prioritize safety: Rust is designed to make whole categories of memory errors impossible by construction.
The diversity of programming languages reflects the diversity of problems that need to be solved with software. Throughout this textbook, Python serves as the main example language because it is readable and commonly used in education. But the ideas introduced here — syntax, semantics, compilation, debugging — apply to any language.
Learning one language well makes learning the next one much easier, because all languages share a common conceptual core. Section 6.10 returns to this idea.
When a programmer writes a program in a high-level language, what they produce is called source code. Source code is text — written in a plain text format, saved in a file, and expressing instructions using the vocabulary and rules of a particular programming language.
Source code is both human-readable and machine-processable. This dual nature is important. Humans need to read, understand, modify, and maintain source code. Machines need to process it into executable instructions.
Here is a small Python program. It contains several ideas this chapter will build on.
# This program calculates the area of a rectangle.
length = 12
width = 7
area = length * width
print("The area is:", area)
Even without knowing Python, most readers can form a rough understanding: it sets up values for length and width, multiplies them, and displays the result. This readability is intentional.
An important distinction: source code is not the program that actually runs. It is the human-readable description of a program. Think of source code as a recipe. A recipe describes what to do in human language. Following the recipe — actually cooking the dish — is a different process. Source code must be translated before a computer can execute it. That translation step is what Section 6.5 explains.
Source code is stored in plain text files. File extensions indicate the language by convention:
.py — Python source files.js — JavaScript source files.java — Java source files.c — C source files.html — HTML source filesEvery programming language is governed by two related but distinct sets of rules: syntax and semantics. Understanding the difference is one of the most useful conceptual tools a programmer can have. It explains why some mistakes are caught immediately and others hide until a program runs — or hide even longer.
Syntax refers to the rules that govern the form and structure of statements in a language — what sequences of symbols are valid and what sequences are not. Programming languages have much stricter syntax than natural languages because computers cannot tolerate ambiguity. If a rule says a function definition must begin with def, every function definition must begin with def. No exceptions.
area = length * width
area = length * * width
The double * * is not a valid operator in Python. A syntax check flags this immediately and the program will not run at all until it is corrected.
Semantics refers to the meaning of statements — what they actually cause to happen. A statement can be syntactically correct (properly formed) but semantically wrong (it does not do what the programmer intended).
area = length + widtharea = length * widthThink of syntax as the formal review of a legal contract — checking structure, format, required signatures. Semantics is what the contract actually means and does once it passes formal review. Both matter: a contract can be perfectly formatted but still have clauses that cause the wrong outcome.
| Concept | Definition | Detected by | Example |
|---|---|---|---|
| Syntax | Rules governing the form and structure of statements | Compiler or interpreter, before running | Missing parenthesis, misspelled keyword |
| Semantics | Rules governing the meaning of statements — what they do | The programmer, through testing | Using + when * was intended |
Source code is not written only for computers. It is written for people — the programmer who wrote it, the teammates who maintain it, the future programmer who needs to fix a bug months later. This is why programming languages include a feature called comments.
A comment is text in source code that the language ignores completely when running the program. Comments exist purely for human readers. In Python, a comment begins with the # character. Everything from the # to the end of the line is treated as a comment.
# Calculate the total cost including tax.
price = 49.99
tax_rate = 0.08
tax = price * tax_rate
total = price + tax # Add tax to the original price.
print(total)
Both comments are completely ignored when Python runs the program — but they help any reader understand the purpose of the calculation. Now consider the same program without comments or meaningful names:
p = 49.99
r = 0.08
t = p * r
tot = p + t
print(tot)
This produces exactly the same result. But the meaning is much less clear. What is p? What is r? A reader must work harder to reconstruct the intent — and harder still if they return to this code after six months.
A useful guideline: comments should explain why, not what. The code itself shows what is happening. A good comment explains why that approach was chosen or what assumption the code depends on.
# Multiply price by tax_rate.
tax = price * tax_rate
# Tax rate is fixed at 8% for this region.
# Update this value if the region changes.
tax = price * tax_rate
Not every line needs a comment. Commenting too much clutters code and creates maintenance work — if the code changes but the comment is not updated, the stale comment becomes actively misleading. Comment when the intent is not obvious; do not restate what the code already shows.
total = price - tax when they intended to add tax to the price. Is this a syntax error or a semantic error? Explain.x, y2, tmp, r. Describe the situation each might represent.# Divide by 60 to convert seconds to minutes.minutes = seconds / 60Source code must be translated into a form the computer can execute. Two main approaches handle this translation: interpretation and compilation. Many languages use variations or combinations of both.
A compiler is a program that reads source code and translates it entirely into another form — typically machine code — before the program runs at all. The compilation step happens separately. If the source code is valid, the compiler produces an executable file that the operating system can run. Languages like C, C++, Rust, Go, and Swift use compilation.
| Compilation | Detail |
|---|---|
| Advantage | Compiled programs typically run fast — translation is done once in advance |
| Advantage | Errors caught before the program ever runs |
| Advantage | Distributed program does not require source code or the compiler |
| Disadvantage | Compilation step adds time during development |
| Disadvantage | Compiled executables are typically specific to a processor and OS |
An interpreter is a program that reads source code and executes it directly, line by line, without producing a separate compiled executable first. When you run a Python program, Python's interpreter reads the source and executes each statement in sequence. The source code is present and processed at runtime. Python, Ruby, and many scripting languages use interpretation.
| Interpretation | Detail |
|---|---|
| Advantage | No separate compilation step; changes take effect immediately |
| Advantage | Easier to experiment interactively |
| Advantage | Same source code can run on any system that has the interpreter |
| Disadvantage | Typically runs more slowly — translation overhead occurs during execution |
| Disadvantage | Errors that occur later in the program are not caught until that code runs |
Many modern language implementations use a hybrid approach. Python compiles source code to an intermediate representation called bytecode, which is then executed by a virtual machine. Java does something similar — Java source code is compiled to Java bytecode, which runs on the Java Virtual Machine (JVM). This approach attempts to gain advantages of both compilation and interpretation.
The practical takeaway: when you write Python and run it, something translates it into execution. The exact mechanism depends on the implementation. What matters most conceptually is that source code does not run directly — it always goes through some translation process.
When a program is running, it is said to be at runtime. Understanding what happens at runtime — and what can go wrong there — is essential for programming.
| Stage | What Happens | Errors Caught |
|---|---|---|
| Write time | Programmer types source code in an editor | Some editors highlight obvious problems immediately |
| Compile time | Compiler processes source code (compiled languages) | Syntax errors; some type errors |
| Load time | Executable is loaded into memory before starting | Some structural errors |
| Runtime | Program is actively executing — instructions run, data is processed | Runtime errors; logic errors only visible through testing |
The state of a program at any point during execution includes: the current instruction being executed, the values stored in all variables, which function the program is currently inside, and any data structures in memory. Understanding state is fundamental to debugging — errors are often caused by state reaching an unexpected value.
A program that never terminates has entered an infinite loop — a sequence of instructions that repeat forever without end. This is a common error that Chapter 8 discusses in detail.
Errors in programs are sometimes called bugs. The process of finding and fixing them is called debugging. Chapter 10 covers debugging in depth. Here, the goal is to introduce the three major categories of errors and understand why they behave differently.
A syntax error occurs when code violates the grammatical rules of the programming language. The language tool detects syntax errors and refuses to proceed. The programmer must fix the syntax before anything else can happen.
print("The area is:", area — closing parenthesis ) is missing.print("The area is:", area)A runtime error occurs while a program is running. The program starts, executes correctly for a while, then encounters a situation it cannot handle. It stops with an error message.
numerator = 10
denominator = 0
result = numerator / denominator
print(result)
ZeroDivisionError and stops. The error could not be predicted at compile time — it depends on the data values present at runtime.A logic error occurs when a program runs without producing any error message but does the wrong thing. The program is syntactically valid and runs to completion — but its output is incorrect because the programmer's reasoning was flawed. Logic errors are the most difficult to find. There is no automatic signal.
a = 10
b = 20
c = 30
average = a + b + c / 3
print(average)
40.0 — but the correct average is 20.0.c / 3 first (operator precedence), giving 10 + 20 + 10 = 40. No error is reported.average = (a + b + c) / 3 — parentheses force the addition to happen first.| Error Type | When Detected | Cause | Effect |
|---|---|---|---|
| Syntax Error | Before running | Violates language grammar | Program does not run at all |
| Runtime Error | During running | Impossible operation encountered | Program stops with error message |
| Logic Error | During testing | Programmer's reasoning is wrong | Program runs but produces wrong results |
Writing, running, testing, and debugging programs requires tools. Understanding those tools at a basic level is part of understanding how programming works in practice.
Any text editor can open and save source code files, but code editors are text editors designed specifically for programming. They provide features that make programming easier:
An Integrated Development Environment (IDE) combines a code editor with additional tools in a single application. IDEs typically include a way to run programs directly, a debugger that allows stepping through code one instruction at a time to inspect variable values at each step, a file manager for navigating project files, and often integration with version control systems.
Popular IDEs include PyCharm (for Python), IntelliJ IDEA (for Java), Xcode (for Apple platforms), and Visual Studio (for many languages). Popular standalone code editors include Visual Studio Code, Sublime Text, and Vim.
Many programmers interact with their computer through a terminal — a text-based interface that accepts typed commands. The terminal allows programmers to navigate directories, run programs, compile code, and install tools. Running a Python program from a terminal looks like this:
$ python rectangle_area.py
The area is: 84
The $ represents the terminal prompt. The programmer types the command; the terminal runs the program and displays its output. Chapter 16 (Operating Systems) and Chapter 17 (Software and Development Tools) discuss the terminal in much more detail.
The specific programming environment does not matter greatly for the concepts in this book. Students might use an online environment, a simple code editor with a terminal, or a full IDE. The ideas of syntax, semantics, errors, and execution apply regardless of which tool is used.
A theme runs through all professional programming practice: code communicates. Code communicates to the computer, of course. But it also communicates to people — teammates, reviewers, future maintainers, and the programmer's own future self. The importance of this second kind of communication is easy to underestimate when first learning to program.
In professional software development, programs are read many more times than they are written. A program is written once, but it is read every time someone needs to understand what it does, fix a bug, add a feature, review it for correctness, or adapt it for a new purpose.
Code that works but cannot be read is a liability. It becomes difficult to maintain, difficult to debug, and difficult to extend. The larger a software project, the more this matters. A well-known principle states that code should be written for the next person who reads it — because that person may be you in six months, and you will have forgotten how it works.
Most programming communities develop conventions — informal agreements about how code should be formatted and organized. Following conventions makes code more readable because readers know what to expect. In Python, the widely adopted style guide is called PEP 8. It recommends, for example:
tax_rate, not TaxRate or taxRatearea = length * width, not area=length*widthThese are conventions, not syntax rules. Code that violates them still runs. But code that follows them is much easier for other Python programmers to read. In professional settings, following the community's style conventions is considered a basic courtesy to teammates.
Code review — where other programmers read new code before it is accepted into a project — is a standard professional practice. Code review is only possible because source code communicates in human-readable form. Readable code receives better reviews and benefits more from the process.
Despite the diversity of programming languages, virtually all general-purpose languages share a core set of ideas. Understanding this shared core means that learning a new language is never starting from scratch.
if/elif/else; JavaScript uses if/else if/else. Same concept.while and for; Java adds do-while. Repetition appears everywhere.score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C or below")
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else {
console.log("Grade: C or below");
}
Both programs produce the same output: Grade: B. The Python version uses no semicolons, no curly braces, and no let keyword. The JavaScript version requires all three. But the logical structure — a variable holding a score, a chain of conditions, a corresponding output — is identical.
A programmer who understands the Python version can understand the JavaScript version with minimal additional explanation. Learning one language well prepares students to learn others. The ideas introduced in Python — variables, conditionals, loops, functions, debugging — will transfer when students encounter JavaScript in web development, SQL in databases, or other languages in later courses.
data.csv, but no such file exists.pint("Hello") instead of print("Hello").Read each code example carefully. Answer the questions without running the code.
# This program greets a user.
name = "Jordan"
greeting = "Hello, " + name
print(greeting)
+ operator appear to do here? How does this differ from its use with numbers?temperature = 98
threshold = 100
if temperature > threshold
print("Overheating!")
else:
print("Temperature is normal.")
# Calculate the perimeter of a square.
side = 5
perimeter = side * side
print("Perimeter:", perimeter)
price = 15.00
quantity = 4
discount = 0.10
total = price * quantity
discounted_total = total - (total * discount)
print("Total after discount:", discounted_total)
total after line 4 runs?discounted_total after line 5 runs?For each situation, identify whether it is a syntax error, runtime error, or logic error. Explain in one sentence.
data.txt, but no file with that name exists on the computer.pint("Hello") instead of print("Hello").F = C * 9 / 5 - 32 instead of F = C * 9 / 5 + 32.x = 60
y = 90
z = (x + y) / 2
print(z)
hours = 40
rate = 18.50
pay = hours * rate # Multiply hours by rate.
** means "to the power of" in Python.)
base = 1000
annual_rate = 0.05
years = 10
result = base * (1 + annual_rate) ** years
print(result)
Each scenario describes a situation a programmer encounters. Identify the type of error and describe what the programmer should do next.
A programmer finishes a 30-line program and tries to run it. The terminal immediately displays: SyntaxError: invalid syntax and points to line 17.
What type of error is this? What should the programmer do first?
A programmer runs a sales tax calculator. It runs to completion and displays an answer, but the answer is 10 times too large.
What type of error is this? Why would no error message appear?
A programmer's program processes a list of names. It works correctly for the first five names, then stops with: IndexError: list index out of range.
What type of error is this? What does the message suggest about the problem?
A programmer's program runs but no output ever appears and it never finishes. No error message is displayed.
What has most likely happened? What term describes this condition?
a = 5
b = 3
c = a * b - 2
print("Result:", c)
radius = 7
area = 2 * 3.14159 * radius
print("Area:", area)
(The formula for the area of a circle is π × r².)
a, b, c1, and c2, and was written by someone who no longer works there. Nobody knows exactly what it does. Explain the practical consequences when the company needs to fix a bug or add a feature.These questions review material from Chapters 1 through 6.
Hi. How many characters does this word contain? Using ASCII encoding, how many bits are needed to represent it?TypeError: unsupported operand type(s) for +: 'int' and 'str'. What type of error is this? What has the program most likely tried to do?Chapter 6 described what programming languages are and how they work in general — syntax, semantics, source code, translation, errors, and tools. Chapter 7 begins working inside a program, examining the building blocks of programming in detail: variables, values, data types, expressions, operators, and how programs receive input and produce output. Every concept in Chapter 7 builds directly on the ideas of source code, syntax, and execution introduced here.