MGU Computer Science Series — Computer Science Foundations
Part II: Programming Foundations
Source Code · Syntax · Compilers · Errors · Environments
Chapter 6 of 28
MGU Computer Science Series  ·  Computer Science Foundations  ·  Library Textbook Edition

Chapter 6:
Programming Languages
and Code

What programming languages are, why they exist, how source code becomes execution, and how to read and reason about programs

■ Part II: Programming Foundations ■

■ 10 Sections  •  Chapter 6 of 28 ■

Follows Chapter 5: Algorithms and Instructions  ·  Prepares students for Chapter 7: Variables, Types, and Expressions

Purpose and Overview

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.

Opening Question

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.

10Sections
9Objectives
24Key Terms
8+Code Examples

Learning Objectives

  1. 1Explain why programming languages exist and why there are many of them.
  2. 2Describe the levels of language from machine code to high-level languages.
  3. 3Define source code and explain how it differs from a running program.
  4. 4Distinguish syntax from semantics and give examples of each.
  5. 5Explain the role of comments and why readability matters in code.
  6. 6Describe the difference between a compiler and an interpreter.
  7. 7Identify syntax errors, runtime errors, and logic errors in code examples.
  8. 8Describe the purpose of programming environments and common tools.
  9. 9Explain the shared conceptual core across different programming languages.

Sections at a Glance

Sections 6.1 – 6.2
The Purpose of Programming Languages
Why Languages Exist · Levels of Language · Source Code

Why Programming Languages Exist

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.

The Levels of Language

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.

High
High-Level Languages — Python, JavaScript, Java, C++, Swift, Rust…
Express instructions in terms of variables, conditions, loops, and functions. Readable by people. Must be translated before execution. One line may become dozens of machine instructions. More portable across different hardware.
Mid
Assembly Language
Uses short abbreviations (mnemonics) to represent machine code instructions. Closer to human language than machine code, but still tied closely to a specific CPU. Translated by a program called an assembler.
Low
Machine Code
Binary instructions a CPU executes directly. Specific to a particular processor architecture. Extremely tedious to write. No meaningful names, no reuse, no clarity. The level where computation actually happens.

Why There Are Many Languages

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.

Key Idea

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.

Source Code

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.

What Source Code Looks Like

Here is a small Python program. It contains several ideas this chapter will build on.

Pythonrectangle_area.py
# This program calculates the area of a rectangle.

length = 12
width = 7
area = length * width
print("The area is:", area)
Output
The area is: 84

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 Files

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 files
Sections 6.3 – 6.4
Syntax, Semantics, and Readability
Grammar vs. Meaning · Comments · Readable Code

Syntax and Semantics

Every 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

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.

Correct Syntax
area = length * width
Syntax Error
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

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).

Example 6.3.1
Syntactically valid but semantically wrong
  • Codearea = length + width
  • Syntax?Valid. Every symbol is correctly placed. Python will not complain.
  • Semantics?Wrong. The area of a rectangle is length multiplied by width, not added. The program runs without errors — but produces incorrect results.
  • Fixarea = length * width
Semantic errors are harder to detect because no tool signals them automatically. Only testing reveals the problem.
A Useful Analogy

Think 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.

ConceptDefinitionDetected byExample
SyntaxRules governing the form and structure of statementsCompiler or interpreter, before runningMissing parenthesis, misspelled keyword
SemanticsRules governing the meaning of statements — what they doThe programmer, through testingUsing + when * was intended

Comments and Readability

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.

What Comments Are

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.

PythonComments in action
# 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:

PythonPoor readability — identical logic
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.

What Good Comments Explain

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.

Less Useful Comment
# Multiply price by tax_rate.
tax = price * tax_rate
More Useful Comment
# Tax rate is fixed at 8% for this region.
# Update this value if the region changes.
tax = price * tax_rate
Over-commenting Is Also a Problem

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.

Practice 6.3 – 6.4Syntax, Semantics, and Comments
  1. What is the difference between a syntax error and a semantic error? Why is a syntax error easier to detect?
  2. A programmer writes total = price - tax when they intended to add tax to the price. Is this a syntax error or a semantic error? Explain.
  3. Rewrite the following variable names to be more readable: x, y2, tmp, r. Describe the situation each might represent.
  4. The following comment restates the code. Rewrite it to explain why:

    # Divide by 60 to convert seconds to minutes.
    minutes = seconds / 60
Sections 6.5 – 6.6
From Source Code to Running Program
Compilers · Interpreters · Runtime · Program State

Interpreters and Compilers

Source 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.

Compilers

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.

Source Code
→
[Compiler]
→
Executable File
→
[CPU]
→
Output
CompilationDetail
AdvantageCompiled programs typically run fast — translation is done once in advance
AdvantageErrors caught before the program ever runs
AdvantageDistributed program does not require source code or the compiler
DisadvantageCompilation step adds time during development
DisadvantageCompiled executables are typically specific to a processor and OS

Interpreters

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.

Source Code
→
[Interpreter]
→
Output (directly)
InterpretationDetail
AdvantageNo separate compilation step; changes take effect immediately
AdvantageEasier to experiment interactively
AdvantageSame source code can run on any system that has the interpreter
DisadvantageTypically runs more slowly — translation overhead occurs during execution
DisadvantageErrors that occur later in the program are not caught until that code runs

The Hybrid Reality

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.

Runtime and Execution

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.

The Timeline of a Program

StageWhat HappensErrors Caught
Write timeProgrammer types source code in an editorSome editors highlight obvious problems immediately
Compile timeCompiler processes source code (compiled languages)Syntax errors; some type errors
Load timeExecutable is loaded into memory before startingSome structural errors
RuntimeProgram is actively executing — instructions run, data is processedRuntime 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.

Practice 6.5 – 6.6Translation and Execution
  1. In your own words, what is the difference between a compiler and an interpreter?
  2. A programmer uses an interpreted language. She adds a bug on line 50 of a 100-line program. At what point will the bug be discovered if lines 1–49 run correctly?
  3. A compiled program is distributed to users. Those users do not have the compiler installed. Can they still run the program? Explain why or why not.
  4. Name two kinds of errors that can only be discovered at runtime rather than before the program runs.
Sections 6.7 – 6.10
Errors, Environments, and the Language Landscape
Three Error Types · Tools · Code as Communication · Shared Ideas Across Languages

Syntax Errors and Logic Errors

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.

Syntax Errors

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.

Example 6.7.1
A syntax error — missing closing parenthesis
  • Errorprint("The area is:", area — closing parenthesis ) is missing.
  • EffectPython reports a syntax error and will not run the program at all until it is fixed.
  • Fixprint("The area is:", area)
Syntax errors are the easiest category to find — the tool reports exactly where the problem is.

Runtime Errors

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.

Example 6.7.2
A runtime error — division by zero
  • Code numerator = 10 denominator = 0 result = numerator / denominator print(result)
  • What HappensThe first two lines run fine. When Python reaches the division, it produces a ZeroDivisionError and stops. The error could not be predicted at compile time — it depends on the data values present at runtime.
Runtime errors stop the program and produce an error message — but only when the problem is actually encountered.

Logic Errors

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.

Example 6.7.3
A logic error — operator precedence
  • Code a = 10 b = 20 c = 30 average = a + b + c / 3 print(average)
  • Output40.0 — but the correct average is 20.0.
  • WhyPython evaluates c / 3 first (operator precedence), giving 10 + 20 + 10 = 40. No error is reported.
  • Fixaverage = (a + b + c) / 3 — parentheses force the addition to happen first.
Logic errors are only revealed by testing — comparing the program's output to what it should produce.
Error TypeWhen DetectedCauseEffect
Syntax ErrorBefore runningViolates language grammarProgram does not run at all
Runtime ErrorDuring runningImpossible operation encounteredProgram stops with error message
Logic ErrorDuring testingProgrammer's reasoning is wrongProgram runs but produces wrong results

Programming Environments

Writing, running, testing, and debugging programs requires tools. Understanding those tools at a basic level is part of understanding how programming works in practice.

Code Editors

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:

Code Editor Features
  • Syntax highlighting — keywords, strings, numbers, and comments display in different colors
  • Auto-indentation — the editor maintains proper indentation as code is written
  • Bracket matching — places the cursor next to an opening bracket; the editor highlights the matching closing bracket
  • Line numbering — line numbers appear alongside code, useful when acting on error messages

IDEs

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.

The Terminal

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:

Terminal
$ 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.

For This Textbook

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.

Code as Communication

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.

Programs Are Read, Not Just Run

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.

Style Conventions

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:

PEP 8 Examples (Python Style Conventions)
  • Use lowercase names with underscores for variables and functions: tax_rate, not TaxRate or taxRate
  • Put a space on each side of an operator: area = length * width, not area=length*width
  • Limit lines to a reasonable length so they do not extend off the screen

These 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.

Many Languages, Shared Ideas

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.

The Shared Conceptual Core
  • Variables and values — a way to name data and refer to it by name. Syntax differs; the idea is universal.
  • Conditionals — a way to execute different code depending on a condition. Python uses if/elif/else; JavaScript uses if/else if/else. Same concept.
  • Loops — a way to repeat code. Python has while and for; Java adds do-while. Repetition appears everywhere.
  • Functions — a way to group instructions into a reusable unit that can be called by name. Terminology varies; the concept is universal.
  • Input and output — a way to receive data and produce results. Mechanisms vary widely; the need is universal.
  • Data types — distinctions between numbers, text, true/false values, and collections. Every language has them.
  • Errors — every language has syntax rules, and violating them produces errors. Every language can experience runtime failures and logic errors.

Python and JavaScript Side by Side

Python
score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
else:
    print("Grade: C or below")
JavaScript
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.

Practice 6.7 – 6.10Errors, Tools, and Language Concepts
  1. Classify each of the following as a syntax error, runtime error, or logic error. Explain your answer.

    a. A program attempts to open a file named data.csv, but no such file exists.
    b. A programmer writes pint("Hello") instead of print("Hello").
    c. A program calculates the average of two numbers by dividing their sum by 3 instead of 2.
    d. A program is missing a closing bracket on line 14.
  2. A student argues: "Learning Python means I have to start over completely when I learn JavaScript." Do you agree? Name two specific concepts that transfer between the two languages.
  3. What is a debugger, and how does it differ from simply reading the source code?
  4. Explain why a company with publicly available source code has an especially strong reason to prioritize readability and comments.

Chapter Summary

Key Terms Review

assembly language
A low-level programming language that uses short mnemonics to represent machine code instructions. Translated by an assembler.
bug
An error in a program. The process of finding and fixing bugs is called debugging.
bytecode
An intermediate representation produced by some language implementations (Python, Java) that is executed by a virtual machine rather than the CPU directly.
code editor
A text editor designed for programming, with features such as syntax highlighting, auto-indentation, and bracket matching.
comment
Text in source code that the language ignores during execution. Written for human readers to explain intent, assumptions, or context.
compiler
A program that translates source code entirely into another form — typically machine code — before the program runs, producing an executable file.
debugging
The process of finding and fixing errors in a program.
executable
A compiled output file that can be run directly by the operating system or CPU without the original source code or compiler.
high-level language
A programming language that expresses instructions in terms of variables, conditions, loops, and functions rather than specific CPU instructions. Readable by people. Requires translation.
IDE
Integrated Development Environment. Combines a code editor, program runner, debugger, and other tools in a single application.
interpreter
A program that reads and executes source code directly, without producing a separate compiled executable. The source code is processed at runtime.
logic error
An error in which a program runs without producing an error message but produces incorrect results due to flawed reasoning in the program's logic.
machine code
Binary instructions that a CPU executes directly. Specific to a particular processor architecture. The lowest level at which software operates.
programming language
A precisely defined formal language that allows humans to express instructions in a form that can be understood, checked, and executed by a computer.
readability
The quality of source code that makes it easy for humans to read, understand, and maintain. Achieved through naming, formatting, comments, and organization.
runtime
The period during which a program is actively executing instructions.
runtime error
An error that occurs during program execution when the program encounters a situation it cannot handle. The program stops with an error message.
semantics
The rules governing the meaning of statements in a programming language — what they actually cause to happen.
source code
The human-readable text of a program, written in a programming language and stored in plain text files.
syntax
The rules governing the form and structure of statements in a programming language — what sequences of symbols are valid.
syntax error
An error that occurs when code violates the grammatical rules of the programming language. Prevents the program from running.
terminal
A text-based interface that accepts typed commands, used to navigate files, run programs, and interact with the operating system.

Code Review

Read each code example carefully. Answer the questions without running the code.

Code Example 1
Greeting program
# This program greets a user.
name = "Jordan"
greeting = "Hello, " + name
print(greeting)
  1. What output does this program produce?
  2. What is the purpose of the first line?
  3. What does the + operator appear to do here? How does this differ from its use with numbers?
Code Example 2 — Contains an Error
Temperature check
temperature = 98
threshold = 100
if temperature > threshold
    print("Overheating!")
else:
    print("Temperature is normal.")
  1. This program contains a syntax error. Identify it precisely and explain what is missing.
  2. After the syntax error is fixed, what output does the program produce?
Code Example 3 — Contains a Logic Error
Square perimeter
# Calculate the perimeter of a square.
side = 5
perimeter = side * side
print("Perimeter:", perimeter)
  1. This program contains a logic error. What is the correct formula for the perimeter of a square?
  2. What does this program currently output? What should it output?
  3. Write the corrected version of the calculation line.
Code Example 4 — Trace
Discounted price
price = 15.00
quantity = 4
discount = 0.10
total = price * quantity
discounted_total = total - (total * discount)
print("Total after discount:", discounted_total)
  1. Trace this program step by step. What is the value of total after line 4 runs?
  2. What is the value of discounted_total after line 5 runs?
  3. What does the program print?

Syntax and Semantics Practice

For each situation, identify whether it is a syntax error, runtime error, or logic error. Explain in one sentence.

  1. A program attempts to read a file named data.txt, but no file with that name exists on the computer.
  2. A programmer writes pint("Hello") instead of print("Hello").
  3. A program calculates the average of two numbers by dividing their sum by 3 instead of 2.
  4. A program is missing a closing parenthesis at the end of a function call.
  5. A program tries to divide a number by a variable, and the variable holds the value 0 when the program runs.
  6. A program converts Celsius to Fahrenheit using F = C * 9 / 5 - 32 instead of F = C * 9 / 5 + 32.
  7. A program uses a reserved keyword as a variable name, which the language does not allow.

Readability and Comments Practice

  1. The following code has poor variable names. Rewrite it using meaningful names without changing what the program does.
    x = 60
    y = 90
    z = (x + y) / 2
    print(z)
  2. The following comment merely restates the code. Rewrite it to explain something more useful.
    hours = 40
    rate = 18.50
    pay = hours * rate  # Multiply hours by rate.
  3. Write two comments for the following code that would help a reader understand its purpose and logic. (Note: ** means "to the power of" in Python.)
    base = 1000
    annual_rate = 0.05
    years = 10
    result = base * (1 + annual_rate) ** years
    print(result)

Debugging Scenarios

Each scenario describes a situation a programmer encounters. Identify the type of error and describe what the programmer should do next.

Scenario 1

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?

Scenario 2

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?

Scenario 3

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?

Scenario 4

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?

Chapter 6 Checkpoint

Chapter 6 Checkpoint
Complete without assistance — assesses all major concepts from Chapter 6
Section 1 — Vocabulary and Concepts
  1. Explain in your own words why programming languages exist. What problem do they solve?
  2. What is source code? How does it differ from an executable program?
  3. Give one example of a syntax error and one example of a logic error. Explain why each belongs in its category.
  4. What does it mean for two versions of a program to be semantically equivalent?
Section 2 — Compilers and Interpreters
  1. Describe the main difference between a compiler and an interpreter. Give one advantage of each.
  2. A program written in a compiled language is distributed to users who do not have a compiler installed. Can they run it? Explain why.
  3. What is bytecode, and why do some language implementations use it?
Section 3 — Reading Code
  1. Read the following program. What does it output? Trace each line. a = 5
    b = 3
    c = a * b - 2
    print("Result:", c)
  2. The following program has a logic error. Identify it and write the corrected version: radius = 7
    area = 2 * 3.14159 * radius
    print("Area:", area)
    (The formula for the area of a circle is π × r².)
Section 4 — Readability and Communication
  1. Why do professional programmers say that code should be written for the next person who reads it?
  2. What is a code review? Why does it require readable source code to work well?
  3. Name two features that a code editor provides that a basic text editor does not.
Section 5 — Shared Ideas Across Languages
  1. A student who has learned Python begins learning JavaScript. List three specific concepts from Python that will transfer directly to JavaScript.
  2. Name two reasons why there are many different programming languages rather than just one.

Real-World Applications

  1. Every major web browser executes JavaScript programs. When you load a web page with interactive elements — a form that validates input, a button that shows or hides content — JavaScript is running. Identify two interactive features you have seen on a website and describe, in general terms, what conditions or loops the underlying code might use.
  2. Operating systems are typically written in compiled languages like C. Web scripts and automation tools are often written in interpreted languages like Python. Based on what you learned about compilers versus interpreters, explain why each choice makes sense.
  3. Many large software projects have public repositories where anyone can read the source code. Explain why readability matters in this context. Who reads the code, and why does clear naming and good comments help them?
  4. A company's internal tool has no comments, variable names like 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.

Mixed Review

These questions review material from Chapters 1 through 6.

  1. (Chapter 4) A text file contains the word Hi. How many characters does this word contain? Using ASCII encoding, how many bits are needed to represent it?
  2. (Chapter 3) What is decomposition? Give an example of how decomposition would apply to writing a program that calculates the total cost of items in a shopping cart.
  3. (Chapter 5) Write a pseudocode algorithm that accepts a temperature in Celsius and outputs whether it is below freezing (less than 0°C), at freezing (exactly 0°C), or above freezing.
  4. (Chapter 2) In computing, what does "output" mean? Name two forms of output a program can produce.
  5. (Chapter 6) A student runs a program and gets this error: TypeError: unsupported operand type(s) for +: 'int' and 'str'. What type of error is this? What has the program most likely tried to do?
Looking Ahead
Chapter 7: Variables, Types, and Expressions

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.

MGU Library Connection
  • Python Quick Reference — Appendix D of this textbook
  • Pseudocode and Flowchart Reference — Appendix C of this textbook
  • Debugging and Testing Reference — Appendix E of this textbook
  • Python Programming Foundations — the next course in the MGU Computer Science pathway
  • Web Development Foundations — covers HTML, CSS, and JavaScript in depth
  • MGU Glossary entries: source code, compiler, interpreter, syntax, semantics, runtime, IDE