MGU Computer Science Series — Programming with Python
Part I: Getting Started with Python
Code · Logic · Data · Files · Functions · Objects · Projects
Chapter 1 of 30
1
MGU Computer Science Series  ·  Programming with Python  ·  Library Textbook Edition

Chapter 1:
What Programming
with Python Studies

Programming as a disciplined practice — reading code, writing code, tracing execution, debugging errors, and building programs that solve real problems

■ Part I of VII  ·  Getting Started with Python ■

■ 9 Sections  •  Chapter 1 of 30 ■

Gateway chapter — no prior programming experience required

Chapter Introduction and Learning Objectives

Programming is the practice of writing precise instructions that a computer can execute. That sentence is short, but it contains an important idea. A computer does not know what you want. It does not guess, infer, or interpret. It follows instructions precisely. If those instructions are clear and correct, the computer does exactly what you intended. If those instructions contain a mistake, even a small one, the computer does something different from what you intended — or it stops entirely and reports an error.

This chapter opens the door to that practice. Before you begin writing code, you need a clear picture of what programming actually is, what Python is, and how programmers think about the work. You need to understand that programming involves not only writing code, but reading code, tracing execution, testing assumptions, finding errors, and steadily improving programs over time. That is what this chapter provides.

Opening Question

You have a list of one hundred student scores and you need to find the average. You have a file of five hundred product names and you need to find all the ones that start with the letter A. You receive a number from a user and you need to tell them whether it is even or odd. What do these three problems have in common? Each one has a clear input, a clear result you want, and a procedure you can describe precisely. Python gives you a way to express that procedure, run it on real data, and check whether it produces the right answer. By the end of this textbook, you will be able to solve all three problems and many more like them.

9Sections
10Objectives
19Key Terms
30Total Chapters

Learning Objectives

By the end of this chapter, you should be able to:

  1. 1Explain what programming is and why precision is essential.
  2. 2Describe what Python is and why it was designed with readability in mind.
  3. 3Explain what a program is and what sequential execution means.
  4. 4Distinguish between source code and execution, and explain the role of the Python interpreter.
  5. 5Explain why reading code is as important as writing code.
  6. 6Describe programming as a problem-solving practice, including the role of problem decomposition.
  7. 7Distinguish between syntax errors, runtime errors, and logic errors, and give an example of each.
  8. 8Name at least five real-world domains where Python is used.
  9. 9Apply at least four effective habits for studying programming.
  10. 10Read a short Python program and explain in plain language what each line does.

Sections at a Glance

Sections 1.1 – 1.4
What Programming Is, What Python Is, and How Programs Run
Instructions · Sequential Execution · Source Code · The Python Interpreter

What Programming Studies

Programming is the practice of writing instructions that a computer can execute.

That sentence is short, but it contains an important idea. A computer does not know what you want. It does not guess, infer, or interpret. It follows instructions precisely. If those instructions are clear and correct, the computer does exactly what you intended. If those instructions contain a mistake, even a small one, the computer does something different from what you intended, or it stops entirely and reports an error.

This precision is both the challenge and the power of programming.

When you write a recipe, you expect a human reader to fill in missing steps, use judgment when something seems off, and adapt to the situation. When you write a program, you cannot rely on any of that. The computer will not add salt because it seems like the right time. It will not notice that you forgot a step. It will follow your instructions exactly as written, in the order you wrote them, no more and no less.

Learning to write instructions precisely is a skill. It takes practice, attention, and patience. But it is not magic. It is not reserved for people with special abilities. It is a craft that rewards careful thinking, systematic testing, and steady improvement.

Programming is also more than just typing code. The full scope of the practice includes:

Design
Plan Before You Write
Think through a solution in plain language before writing a single line of Python. Understand what the program needs to do and how it will do it.
Reading
Understand Code Before Writing It
Read code written by yourself and others. Follow the logic. Predict what will happen before running it. Good programmers are excellent readers.
Tracing
Follow Execution Step by Step
Track what each instruction does and what values each variable holds at each moment. Tracing is how programmers understand what a program actually does.
Testing
Check That Programs Are Correct
Run programs with known inputs and check whether the outputs are right. Testing is not something you do once at the end. You test throughout development.
Debugging
Find and Fix Errors
Identify what went wrong, form a hypothesis, change one thing, and test again. Debugging is a core skill, not an afterthought.
Improving
Make Programs Better Over Time
Revise programs to be clearer, more reliable, and more capable. Programs are rarely finished on the first attempt. Improvement is part of the cycle.

This textbook will ask you to practice all of these skills in every chapter — not just writing code, but reading it, tracing it, testing it, debugging it, and improving it.

Study Note

Programming is a skill, not a subject. You do not learn it by reading about it. You learn it by doing it: writing programs, running them, observing results, fixing errors, and repeating. This textbook guides your thinking and introduces ideas in a useful sequence, but the skill only develops through practice.

What Python Is

Python is a programming language.

A programming language is a formal system for writing instructions that a computer can process. Programming languages have precise rules for what counts as a valid instruction, what words and symbols mean, and in what order instructions are executed. These rules are called the language's syntax and semantics.

Python was created by Guido van Rossum and first released in 1991. It was designed from the beginning with readability in mind. Van Rossum wanted a language that would look like plain, structured English as much as possible, without sacrificing the power needed to write serious programs.

Here is a short Python program:

name = "Alex"
print("Hello,", name)
Output
Hello, Alex

Even if you have never written a line of code, you can probably follow what these two lines do. The first line stores the text Alex under the name name. The second line displays a greeting using that stored text. That readability is intentional. Python code, when written well, is often close to a description of what the program does in plain language.

That quality makes Python an excellent first programming language and an excellent language for working through ideas quickly.

Python is now one of the most widely used programming languages in the world. It is used in universities, research labs, companies, government agencies, and independent projects. It is used by beginners learning their first programming concepts and by experienced engineers building complex systems.

Python is a general-purpose language. That means it is not designed for one narrow task. The same language can be used to write a simple grade calculator, a web server, a data analysis pipeline, or a machine learning experiment.

Python's Design Philosophy

Python's design is guided by a set of principles sometimes called the Zen of Python. A few of the most important ideas: Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Readability counts. You will see these values reflected throughout the language. Python rewards writing code that is clear and easy to follow, not code that is clever and compact.

Programs as Instructions

A program is a sequence of instructions.

Instructions are executed one at a time, in order, from top to bottom, unless something tells the program to jump, repeat, or stop. That top-to-bottom execution order is called sequential execution, and it is the default behavior of every Python program you will write in this textbook.

Consider this short program:

print("Step one")
print("Step two")
print("Step three")
Output
Step one
Step two
Step three

When Python runs this program, it executes the first print instruction, then the second, then the third. The output appears in that order. If you swapped two of those lines, the output would change. The order of instructions matters. Programs are not lists of ideas. They are sequences of actions, and the sequence is part of the meaning.

Illustration 1.3.1
Order matters — the same instructions produce different output depending on sequence
  • Version A print("First")
    print("Second")
    Output: First / Second
  • Version B print("Second")
    print("First")
    Output: Second / First
  • Lesson The instructions are identical. Only the order has changed. The output is completely different. In programming, order is meaning.

Later in this textbook, you will learn how to make programs more dynamic. You will write instructions that repeat using loops. You will write instructions that skip or choose between paths using conditionals. You will write reusable collections of instructions called functions. But all of those tools build on the foundation of sequential execution. Programs always execute instructions in a particular order, and understanding that order is one of the central skills of reading and debugging code.

Source Code and Execution

The text of a program is called source code.

Source code is what you write in a file or type into an interactive shell. It is human-readable text, written according to the rules of the programming language. Here is a short piece of Python source code:

temperature = 72
print("The temperature is", temperature, "degrees.")

Source code is not directly executable by a computer's hardware. Computers execute machine code, a very low-level representation of instructions. Something must translate source code into a form the computer can run.

Python uses an interpreter to do this. The Python interpreter reads your source code, understands it according to Python's rules, and executes it one step at a time. When you run a Python program, the interpreter is doing that work.

This means you need two things to run a Python program:

  1. The Python interpreter installed on your computer
  2. A Python source code file or commands typed into an interactive session

Chapter 2 will walk through setting up Python and running your first programs in detail. For now, the key idea is this: you write text in Python syntax, and the Python interpreter executes that text as a program.

Error Messages Are Information

When the interpreter encounters an instruction it cannot understand because of a mistake in your source code, it stops and reports an error message. Here is an example:

print("Hello"
Error
SyntaxError: '(' was never closed

Error messages are not failures. They are the interpreter's way of telling you exactly what went wrong and where. Learning to read error messages clearly is one of the most practical skills you will develop in this course. A beginner who panics at error messages stays stuck. A programmer who reads them carefully moves forward.

Key Habit

When you see an error message, do not close the window or delete your code. Read the message carefully. It almost always tells you the type of problem and the line number where it was detected. That information is the starting point for fixing the error.

Sections 1.5 – 1.7
How Programmers Think: Reading, Problem Solving, and Errors
Code Reading · Problem Decomposition · Syntax · Runtime · Logic Errors

Reading Code Before Writing Code

Many people approach programming by immediately trying to write code. This is understandable. Writing feels productive. But it often leads to confusion, because writing code you do not fully understand is difficult to fix when something goes wrong.

A better habit is to read code before you write it.

Reading code means looking at a program, following its logic carefully, and understanding what it does before you run it. Good programmers read code all the time. They read their own programs to catch errors before running them. They read code written by others to understand how it works. They read documentation and examples to learn new ideas.

This textbook will ask you to read a great deal of code. Each chapter includes activities built around these tasks:

ActivityWhat You DoWhat You Learn
Predict the output Read a short program and write down exactly what you think it will display before running it Whether your mental model of Python is accurate
Trace variable values Follow a program step by step and record the value of each variable after each instruction How data changes as a program executes
Find the bug Read a program containing an error and identify the mistake without running it How to read code critically rather than passively
Explain each line Describe in plain language what each instruction does and why Whether you understand purpose, not just syntax
Compare solutions Read two programs that solve the same problem and identify the differences That there are many ways to write a correct program

These activities are not warm-ups before the real work. They are the real work. Learning to read code carefully is what makes you a good debugger, a good designer, and a good collaborator. The predict-and-check habit is especially powerful: when your prediction matches the output, you have understood the code. When it does not match, that mismatch is valuable — it tells you exactly where your mental model of Python needs adjustment.

Worked Example 1.5.1
Reading a short program before running it
  • The Code x = 5
    y = 10
    print(x + y)
    print(x * y)
  • Read Line 1 The value 5 is stored under the name x. After this line, x holds the value 5.
  • Read Line 2 The value 10 is stored under the name y. After this line, y holds the value 10.
  • Read Line 3 x + y is 5 + 10 which is 15. The program will display 15.
  • Read Line 4 x * y is 5 * 10 which is 50. The program will display 50.
  • Prediction The program will display 15 on one line, then 50 on the next line. Run it and check.

Programming as Problem Solving

Programming is a tool for solving problems.

A problem, in the programming sense, is a situation where you have information, you want a result, and you need a procedure for producing that result from the information. Programming gives you a way to express that procedure precisely, test it, and run it repeatedly.

Consider a few examples:

Information You HaveResult You WantProcedure
A list of student test scores The average score Add all scores, divide by how many there are
A folder of files with inconsistent names All files renamed to a consistent pattern Read each filename, apply the pattern, rename the file
A text passage entered by the user A count of how often each word appears Split the text into words, count each unique word
A temperature in Celsius from the user That temperature converted to Fahrenheit Apply the formula: multiply by 9/5 and add 32

In each case, the program is not magic. It is a clear procedure for transforming input into output.

Good programmers do not jump immediately to code when they face a problem. They first understand what the problem is asking. They identify what information they have and what result they need. They think through a procedure in plain language before writing a single line of Python. Then they translate that procedure into code, test it against examples, and refine it when they discover errors.

That practice — understanding the problem before solving it — is called problem decomposition, and it is one of the most important habits you will develop in this textbook.

The Problem-Solving Cycle

Understand. What exactly does the problem ask for? What information is given? What result is required?

Plan. Describe a procedure in plain language. How will you get from the input to the output?

Write. Translate the procedure into Python, one small step at a time.

Test. Run the program with simple examples where you can verify the result by hand.

Improve. When the program works, ask whether it is as clear and correct as it can be.

Errors, Testing, and Improvement

Every programmer makes errors. This is not a sign of weakness or inexperience. It is the nature of the work. There are three major categories of errors in programming, and each one requires a different approach to find and fix.

Syntax Errors

Syntax errors occur when your code violates the rules of Python's grammar. The interpreter cannot understand what you wrote. It stops before running anything and tells you where the problem is.

print("Hello"
Error
SyntaxError: '(' was never closed

This is a syntax error. The opening parenthesis is not closed. Python reports exactly what is wrong and on which line.

Runtime Errors

Runtime errors occur when your code is grammatically correct but something goes wrong while the program is running. For example, asking Python to divide by zero, or to open a file that does not exist.

x = 10
y = 0
print(x / y)
Error
ZeroDivisionError: division by zero

The syntax is fine. Python understands what the code says. But dividing by zero is not defined, and Python stops and reports the problem at the moment it occurs.

Logic Errors

Logic errors occur when your code runs without error but produces the wrong result. The program does what you told it to do, but you told it to do the wrong thing. These are the hardest errors to find because Python does not report them. Only careful testing and tracing reveals them.

# Intended to calculate the average of three numbers
total = 10 + 20 + 30
average = total / 2   # Bug: should divide by 3, not 2
print(average)
Output
30.0

This runs without error and prints 30.0. But the correct average of 10, 20, and 30 is 20.0. The logic is wrong. Python had no way to know what the programmer intended, only what the programmer wrote.

Common Beginner Mistake

It is tempting to consider a program finished as soon as it runs without error. But running without error is not the same as running correctly. Always test your program against examples where you know the right answer, and verify that the program produces it.

Error TypeWhen It OccursDoes Python Report It?How to Find It
Syntax error Before the program runs Yes — with a message and line number Read the error message carefully
Runtime error While the program is running Yes — with an error type and location Read the traceback and find the failing line
Logic error The program runs and finishes No — Python cannot know the intent Test with known inputs and verify outputs
Sections 1.8 – 1.9
Where Python Is Used and How to Study It Well
Real Applications · Study Habits · Patience and Persistence

What Python Is Used For

Python is used in an enormous range of real applications. Understanding this range helps you see why the foundations you build in this textbook matter beyond the classroom.

Education
Learning and Teaching
Python is widely taught in schools, universities, and online courses because of its readable syntax and gentle learning curve.
Data Science
Analyzing Information
Python is a dominant language for analyzing data, building statistical models, cleaning datasets, and producing visualizations. Libraries like pandas and NumPy are industry standards.
Science
Research Computing
Researchers in physics, biology, chemistry, and astronomy use Python to run simulations, process experimental data, and analyze results.
Automation
Scripting and Workflows
Python is excellent for automating repetitive tasks: renaming files, processing text, downloading data, generating reports, and managing workflows.
Web Development
Building Applications
Frameworks like Django and Flask make it possible to build web applications and APIs in Python, from small sites to large-scale services.
Cybersecurity
Security and Analysis
Security professionals use Python for network scanning, vulnerability testing, log analysis, and building security tools.
Artificial Intelligence
Machine Learning
Python is the primary language of modern machine learning. TensorFlow, PyTorch, and scikit-learn are all Python libraries used by researchers and engineers worldwide.
Everyday Scripting
Personal Tools
People use Python to write small tools that solve specific personal problems: tracking expenses, organizing files, generating personalized messages, or parsing data.

This textbook does not cover all of these areas. Its goal is to teach you the foundations of Python programming that make all of those applications possible. Before you can analyze data, build a web app, or write a machine learning model, you need to know how to write clean, correct, and organized Python programs. That is what this book teaches.

Looking Ahead — The MGU Python Pathway

This textbook covers language foundations: values, variables, control flow, functions, data structures, files, exceptions, and object-oriented basics. Later books in the MGU series build on this foundation for data science, web development, automation, scientific computing, and artificial intelligence. None of those paths are accessible without the foundations you build here.

How to Study Programming Successfully

Programming is a skill, not a subject. The difference matters. You do not learn to program by reading about programming. You learn by writing programs, running them, observing results, fixing errors, and repeating. A textbook can guide your thinking and introduce ideas in a useful sequence, but the skill only develops through practice.

Here are habits that consistently help students learn programming well.

Study Habit Guide
Eight habits for effective programming study
  • Type the code Do not copy and paste examples. Type them yourself. The physical act of writing code forces you to look at every character. It exposes details you would skim over when reading. It builds recognition for common patterns.
  • Predict first Before running any code in this textbook, write down what you think it will do. Then run it and compare. When your prediction is wrong, investigate why. That investigation is where real learning happens.
  • Read errors Error messages are information. They tell you what went wrong and usually point to the approximate location of the problem. Do not panic when you see a red error message. Read it. Understand it. Use it.
  • Work small Do not try to write a complete program at once and then debug everything at the end. Write a small piece. Run it. Confirm it works. Add the next piece. This is called incremental development, and it is one of the most effective programming habits.
  • Explain it If you cannot explain what a line of code does in plain language, you do not fully understand it yet. Practice explaining your programs to yourself or to a classmate. This habit is sometimes called rubber duck debugging — describing code to an imaginary listener forces you to confront gaps in your understanding.
  • Debug carefully When your program does not work, resist the urge to randomly change things until something works. Instead, form a hypothesis about what might be wrong, change one thing, and test. Systematic debugging is much faster than guessing.
  • Review often Programming concepts build on each other. If something from an earlier chapter feels fuzzy, go back and work through it again before moving forward. Fuzzy foundations make later material much harder.
  • Be patient Every programmer, even experienced ones, faces moments where something does not work and they cannot immediately see why. That frustration is normal. It does not mean you lack ability. Patience and persistence are more important than any natural talent.

Chapter Summary

Key Terms

bug
An error in a program that causes it to behave incorrectly or unexpectedly.
debugging
The process of finding and fixing errors in a program.
error message
A report produced by the Python interpreter describing what went wrong and where.
execute
To carry out a program's instructions. The interpreter executes source code.
function
A named, reusable block of instructions. print() is an example of a built-in Python function.
general-purpose language
A programming language not designed for one specific domain, but suitable for many different kinds of programs.
incremental development
The practice of building a program in small steps, testing each step before adding the next.
interpreter
A program that reads source code and executes it. Python uses an interpreter to run programs.
logic error
An error where the program runs without crashing but produces incorrect results because the instructions do not correctly describe the intended procedure.
problem decomposition
The practice of breaking a problem into smaller, more manageable pieces before writing code.
program
A sequence of instructions written in a programming language that a computer can execute.
programming language
A formal system with precise rules for writing instructions that a computer can process.
runtime error
An error that occurs while the program is running, after the interpreter has accepted the syntax.
semantics
The meaning of statements in a programming language. What an instruction actually does when executed.
sequential execution
The default order of execution in a program: instructions run one at a time, from top to bottom.
source code
The text of a program as written by a programmer, in a human-readable programming language.
syntax
The grammatical rules of a programming language. What counts as a valid instruction.
syntax error
An error that occurs when source code violates the grammatical rules of the programming language.
testing
The practice of running a program with known inputs to check whether the outputs are correct.
tracing
Following the execution of a program step by step, tracking variable values and the effect of each instruction.
ActivitiesCode Reading Warm-Up

Read each code example carefully. Do not run it yet. Answer the questions. Then run the code and compare your answers to the actual output.

Exercise 1.1 Three print instructions
print("Python is a programming language.")
print("Programs are sequences of instructions.")
print("Instructions execute in order.")
  1. How many instructions does this program contain?
  2. In what order will the output lines appear?
  3. Write out exactly what the program will display.
Exercise 1.2 Storing a value in a variable
message = "Hello, programmer."
print(message)
  1. What does the first line do?
  2. What does the second line do?
  3. What does the program display?
Exercise 1.3 Two variables and arithmetic
x = 5
y = 10
print(x)
print(y)
print(x + y)
  1. What is the value of x after line 1? What is the value of y after line 2?
  2. What does the third print instruction display?
  3. Does the program change the value of x or y? Explain.
Exercise 1.4 Instructions out of their natural order
print("Line 1")
print("Line 3")
print("Line 2")
  1. What does this program display?
  2. Does the program display lines in numerical order? Why or why not?
  3. What does this tell you about how Python executes instructions?
ActivitiesPredict the Output

For each program, write exactly what you think will be displayed, then run the code to check your prediction.

Exercise 1.5 Arithmetic expressions
print(2 + 3)
print(10 - 4)
print(3 * 7)
Exercise 1.6 Variables and arithmetic
a = 100
b = 25
print(a + b)
print(a - b)
Exercise 1.7 Sequential output
print("First")
print("Second")
print("Third")
print("Done")
ActivitiesProgramming in Everyday Life

Programming concepts appear constantly in everyday life, even outside of computers. These activities help build intuition for how programs work.

  1. Recipe as Program. A recipe is a sequence of instructions. Identify three ways that following a recipe is similar to executing a program. Then identify one important way they are different — one thing a human cook does automatically that a computer program could not.
  2. Write a Precise Procedure. Think of a task you do repeatedly — making coffee, locking the door before leaving, packing a bag. Write the steps as a precise numbered sequence of instructions. Then identify one step where a human fills in missing information automatically, and consider how you would make that step explicit enough for a computer to follow.
  3. Identify the Error Type. For each situation below, identify whether the error is most likely a syntax error, a runtime error, or a logic error: (a) A program prints the wrong answer but runs without error. (b) A program stops immediately with the message SyntaxError: invalid syntax. (c) A program crashes midway through with the message FileNotFoundError. (d) A program calculates the perimeter of a rectangle by adding only two sides instead of all four.
  4. Python in the World. From Section 1.8, choose one application area for Python. Write a short paragraph describing a specific real example of how Python might be used there, what input it would receive, what computation it would perform, and what output or result it would produce.

Common Misconceptions

Misconception 1
"If the program runs without error, it is correct."
A program can run without error and still produce the wrong result. Runtime errors and syntax errors are not the only way a program can fail. Logic errors are often the hardest problems to find precisely because they do not produce error messages. Testing with known inputs and verifying the outputs is required to catch them.
Misconception 2
"Good programmers write code that works on the first try."
Professional programmers write code that does not work on the first try. They debug frequently. They test carefully. They revise. The difference between a beginner and an expert is not that the expert makes no mistakes. It is that the expert knows how to find and fix mistakes efficiently, and does not take errors personally.
Misconception 3
"You need to memorize all of Python's syntax."
You will remember the most common patterns through repeated practice. For everything else, documentation, references, and examples are always available. Programming is not a memory test. It is a reasoning and design practice. What matters is understanding how things work, not reciting rules from memory.
Misconception 4
"Programming is mostly about math."
Many programming problems involve no advanced mathematics at all. Arithmetic and basic algebra appear frequently. But the core skill is logical reasoning: understanding what a problem asks, designing a procedure to solve it, and expressing that procedure precisely. Students who think carefully and reason carefully become good programmers regardless of their prior experience with mathematics.
Misconception 5
"Errors mean you are bad at programming."
Errors mean you are programming. Every programmer produces errors constantly. The habit of reading error messages carefully, forming hypotheses about the cause, and testing fixes systematically is what separates programmers who improve from programmers who stay stuck.
ReviewReview Questions

Recall and Vocabulary

  1. What is sequential execution? Give a one-sentence description and a short Python example.
  2. What is the difference between syntax and semantics in a programming language?
  3. What does the Python interpreter do?
  4. What is source code?
  5. What is the difference between a syntax error, a runtime error, and a logic error? Give a one-sentence description of each.
  6. What does it mean for Python to be a general-purpose language?
  7. What is problem decomposition? Why is it useful?
  8. What is incremental development? How does it reduce debugging effort?

Understanding and Explanation

  1. Why does a computer need instructions to be precise in a way that a human following instructions does not?
  2. Why is reading code considered as important as writing code?
  3. Why are logic errors harder to find than syntax errors?
  4. A classmate says: "I tested my program and it worked." What important information is missing from that statement?
  5. Explain in your own words why the order of instructions in a program matters. Give an example where swapping two instructions would change the result.
  6. Why might a student who is good at mathematics still struggle to learn programming? What additional skills does programming require beyond mathematical ability?

Application and Analysis

  1. For each program below, identify what kind of error is present (syntax, runtime, or logic) and explain how you would fix it.

    (a)
    print("The answer is" 42)
    (b)
    score = 85
    grade = score / 0
    print(grade)
    (c)
    # Should print the sum of 4 and 6
    result = 4 - 6
    print(result)
  2. A student is asked to write a program that converts a temperature from Celsius to Fahrenheit. The formula is: multiply by 9, divide by 5, then add 32. Using the problem-solving cycle from Section 1.6, describe how the student should approach this problem before writing any code.
  3. Look at the following two programs. Both run without error. One of them contains a logic error. Identify which one and explain the mistake.

    Program A:
    # Find the average of 10 and 20
    total = 10 + 20
    average = total / 2
    print(average)
    Program B:
    # Find the average of 10, 20, and 30
    total = 10 + 20 + 30
    average = total / 2
    print(average)
  4. In your own words, describe the rubber duck debugging technique. Why might explaining your code to an imaginary listener help you find errors?

Design and Synthesis

  1. Write the first paragraph of a brief guide titled What Is Python? aimed at a family member who has never studied programming. Your paragraph should be accurate, use no unexplained jargon, and make clear why Python is worth learning.
  2. Section 1.9 describes eight study habits for programming. Choose the three you believe will be most important to you personally. For each one, write a sentence explaining why you chose it and how you plan to apply it in this course.
Chapter 1 Checklist
Confirm your understanding before moving to Chapter 2
Concepts
  • I can explain what programming is and why precision is essential.
  • I can describe what Python is and what makes it readable and general-purpose.
  • I can explain sequential execution and give an example.
  • I can distinguish between source code and execution.
  • I can explain what the Python interpreter does.
  • I can distinguish between syntax errors, runtime errors, and logic errors.
  • I can explain why logic errors are the hardest to find.
  • I can describe problem decomposition and explain why it is useful.
Reading and Analysis
  • I can read a short Python program and predict what it will display before running it.
  • I can trace a short program and state the value of each variable after each instruction.
  • I can identify an error in a short program and describe how to fix it.
  • I can explain what each line of a short program does in plain language.
Study Habits
  • I understand why I should type code myself rather than copy and paste examples.
  • I understand why I should predict output before running programs.
  • I understand why I should read error messages carefully rather than panic at them.
  • I understand what incremental development means and how it reduces debugging effort.
Preview — Chapter 2
Setting Up Python and Running Programs

Chapter 1 introduced programming as a practice and Python as a language. Chapter 2 will make things concrete. You will install Python if you have not already, explore the interactive shell, write your first Python script files, and learn how to run programs from a terminal or code editor. You will also learn about file paths, folder organization, and common setup problems. By the end of Chapter 2, you will have Python running on your machine and you will have successfully executed your first complete program.

MGU Library Connection
  • Programming with Python — Appendix A: Installing and Running Python
  • Programming with Python — Appendix D: Common Python Error Messages
  • Programming with Python — Appendix E: Debugging Checklist
  • Companion resource: Python Syntax Quick Reference
  • Companion resource: Variable Tracing Worksheet
  • Prerequisite: Computer Science Foundations — Chapter 1 (What Computer Science Studies)
  • Next course: Data Structures and Algorithms (requires this textbook as prerequisite)