MGU Computer Science Series — Programming with Python
Part I: Getting Started with Python
Interpreter · Scripts · Editors · Terminal · Paths · First Program
Chapter 2 of 30
2
MGU Computer Science Series  ·  Programming with Python  ·  Library Textbook Edition

Chapter 2:
Setting Up Python
and Running Programs

The interpreter, interactive mode, script mode, code editors, the terminal, file paths, and your first complete Python program

■ Part I of VII — Getting Started with Python ■

■ 10 Sections  •  Chapter 2 of 30 ■

Practical setup chapter — focuses on the tools that make every chapter that follows possible

Chapter Introduction and Learning Objectives

Before you write a single meaningful Python program, you need to know how Python works as a piece of software. You need to know what the Python interpreter is, how to install it, how to give it instructions interactively, how to save a complete program as a file, how to run that file, and how to make sense of what happens when something goes wrong. These are not exciting ideas — but they are the tools that make every idea in this book reachable.

This chapter is practical. Its goal is a narrow but critical one: by the time you reach Chapter 3, you should be able to open Python, type expressions and see results, save a script file, run it, read its output, and fix the most common setup problems on your own. Those four skills — open, type, save, run — unlock everything that follows.

Chapter Purpose

Before you can write and run Python programs, you need to know how Python works as a tool. This chapter explains what Python is as a piece of software, how to install it, how to use the interactive shell, how to write and save script files, how to use a code editor, how to work with terminals at a basic level, how to understand file paths well enough to run your programs, and how to troubleshoot the most common setup problems beginners face.

By the end of this chapter you should be able to open a Python interactive session, type a few expressions, save a small Python script, run it, and understand what happened.

10Sections
11Objectives
15Key Terms
6Troubleshooting Scenarios

Learning Objectives

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

  1. 1Explain what the Python interpreter does and why it is needed to run Python code.
  2. 2Describe the difference between Python 2 and Python 3 and explain why Python 3 is used in this textbook.
  3. 3Distinguish between interactive mode and script mode, and explain when each is appropriate.
  4. 4Name at least three code editors suitable for Python and describe one advantage of each.
  5. 5Use basic terminal commands to navigate folders, list files, and run a Python script.
  6. 6Explain what a file path is and distinguish between absolute and relative paths.
  7. 7Create and save a Python script file with a correct name and location.
  8. 8Run a Python script from inside a code editor and from the terminal.
  9. 9Explain the difference between how values appear in interactive mode versus script mode.
  10. 10Diagnose and address at least four common Python setup problems.
  11. 11Write, run, and explain a small Python program that uses print(), input(), a variable, and a comment.

Sections at a Glance

Sections 2.1 – 2.3
The Tools: Interpreter, Modes, and Editors
Python Interpreter · Interactive Mode · Script Mode · Code Editors

Python 3 and the Python Interpreter

Python is a programming language, but it is also a piece of software. When you write a Python program, you write plain text in a file. That text is your source code. Python does not magically understand your code on its own. A program called the Python interpreter reads your source code and carries out your instructions.

The interpreter is the bridge between what you write and what the computer does. Without it, a Python file is just text. With it, that text becomes a running program.

Python versions

Python has a long history. The version that matters for this textbook is Python 3. Python 3 is the current, supported, actively developed version of the language. An older version, Python 2, existed for many years and is now retired. Python 2 and Python 3 are not fully compatible — some syntax and behaviors differ between them in ways that matter.

This textbook uses Python 3 throughout. All examples, exercises, and projects are written for Python 3.

When you download Python, you will see a specific version number such as 3.11.4 or 3.12.0. The first digit is the major version (3). The second digit is the minor version. Minor versions add features and fix bugs. For the topics in this textbook, any Python 3.8 or later version works well. If you already have Python 3 installed, check whether it is reasonably recent before installing a new version.

What the interpreter does

When you run a Python program, the interpreter goes through your code, translates it into instructions the computer can execute, and runs those instructions. This all happens quickly and automatically — you do not usually see the translation step. You see the results.

The interpreter can work in two different modes: interactive mode and script mode. You will use both. The next section explains the difference.

Checking your version

To check which Python version is installed, open a terminal and type python --version or python3 --version. Python will print something like Python 3.11.4. If you see Python 2.x.x, you need to install Python 3 separately.

Interactive Mode and Script Mode

Interactive mode

In interactive mode, the Python interpreter waits for you to type one line of code at a time, runs it immediately, and shows you the result. This is sometimes called the Python shell or the REPL, which stands for Read, Evaluate, Print, Loop.

When you open interactive mode, you see a prompt that looks like this:

Interactive shell prompt
>>>

The three arrows are called the primary prompt. They mean Python is waiting for your input. You type a line of Python code, press Enter, and Python immediately evaluates it and prints the result if there is one.

Example 2.2.1
A short interactive mode session
  • Input>>> 2 + 3 — You type an arithmetic expression.
  • Output5 — Python evaluates it and prints the result immediately.
  • Input>>> print("Hello") — You call a function.
  • OutputHello — The function runs and displays its output.
  • Input>>> name = "Alex" — You store a value in a variable. No output — assignment is silent.
  • Input>>> name — You type just the variable name.
  • Output'Alex' — Interactive mode shows you the value. This only works in interactive mode; in a script you would need print().

Interactive mode is useful for trying a short expression to see what it produces, testing whether a function works the way you expect, exploring how a data type behaves, or quickly calculating something. It is not a good place to write a full program, because once you close the session, everything you typed is gone.

Script mode

In script mode, you write your Python code in a plain text file, save the file, and then tell Python to run the entire file. This is how real programs are written and run.

A Python script file has a name that ends in .py. For example: hello.py, calculator.py, grade_checker.py. The .py extension tells operating systems and editors that the file contains Python code.

When you run a script file, Python reads through the entire file from top to bottom and executes all the instructions. Nothing is printed automatically — you have to use print() to display output. Script mode is what you will use for every real program in this textbook.

Comparison

FeatureInteractive ModeScript Mode
How you use itType one line at a timeWrite a file, then run it
ResultsShown immediately after each lineShown only when print() is called
Saved?No — lost when you close the sessionYes — saved in a .py file
Good forExploring, experimenting, testing small ideasWriting complete programs
A common beginner mistake

In interactive mode, typing a variable name displays its value automatically. In a script file, it does not — you must use print(variable_name). Many beginners write scripts and wonder why nothing appears. The answer is almost always a missing print().

Code Editors and Development Environments

You write Python scripts in a text editor or a development environment. A plain text editor is enough. A development environment adds extra tools that help you write, run, and debug code more efficiently.

Why not a word processor?

Word processors like Microsoft Word save files with hidden formatting codes. Python needs plain text with no formatting. Always use a tool designed for code, not a word processor. Even a single invisible formatting character can cause Python to fail.

Options for writing Python code

Option 1
IDLE
IDLE stands for Integrated Development and Learning Environment. It comes installed automatically with Python. IDLE includes both an interactive shell and a simple file editor. For a beginner just getting started, IDLE works well. It is modest in features but sufficient for early learning. To open IDLE: after installing Python, look for IDLE in your applications list.
Option 2
Visual Studio Code
VS Code is a free, popular code editor made by Microsoft. It works on Windows, macOS, and Linux. With the Python extension installed, VS Code provides syntax highlighting, error underlining, a built-in terminal, and many other features. Most working programmers use an editor like VS Code or something comparable.
Option 3
Thonny
Thonny is a Python editor designed specifically for beginners. It comes with its own Python interpreter bundled in, which simplifies setup. Thonny shows variable values, traces execution visually, and includes a built-in debugger that beginners find useful. If you want a simple setup experience, Thonny is a strong choice.
Which editor should you choose?

If you are unsure, IDLE is the safest starting point — it is already installed with Python. Thonny is excellent if you want a beginner-friendly experience with visual debugging. VS Code is the right choice if you want to build habits with a tool you will likely use long-term. Any of these will work for everything in this textbook.

What to look for in a code editor

For this course, choose a code editor that saves files as plain text, shows Python syntax with color highlighting (called syntax highlighting), uses a monospace font where every character takes the same width, lets you open and save .py files easily, and has a way to run your Python file directly or open a terminal.

Sections 2.4 – 2.5
Navigation: Terminals and File Paths
Terminal Commands · Working Directory · Absolute and Relative Paths

Terminals and Command Lines at an Introductory Level

A terminal is a text-based window where you type commands and the computer responds with text. Terminals go by different names depending on the operating system: on Windows, the options include Command Prompt, PowerShell, and Windows Terminal; on macOS, the application is called Terminal (found in Applications → Utilities); on Linux, it may be called Terminal, Console, or Bash.

The terminal is where you will often run Python scripts. You do not need to become a terminal expert right now. You need to know enough to navigate to a folder and run a Python file.

Basic terminal commands

ActionWindowsmacOS / Linux
Print current foldercd (with no argument)pwd
List files in current folderdirls
Move into a foldercd foldernamecd foldername
Move up one folder levelcd ..cd ..
Check Python versionpython --versionpython3 --version
Run a Python scriptpython myscript.pypython3 myscript.py
Example 2.4.1
Navigating to a folder and running a script — macOS/Linux
  • StartYou open the terminal. Your current directory is your home folder: /Users/alex
  • NavigateType cd Documents/python_projects/chapter_02 and press Enter. You are now inside the chapter_02 folder.
  • VerifyType ls to list files. You see hello.py in the output, confirming your file is here.
  • RunType python3 hello.py and press Enter. Python runs your script and its output appears immediately below.
A note about fear of the terminal

Many beginners feel uncomfortable with the terminal at first. This is normal. Terminals feel unforgiving because there are no buttons to click. But the terminal will not damage anything if you type an unknown command — it will usually just say the command was not found. Approach terminal practice the same way you approach Python practice: try, observe, adjust, and try again.

Files, Folders, and Paths

Your computer stores files inside folders. Folders can be inside other folders. This creates a file system tree — a nested structure of folders and files. Understanding file paths matters in Python because you need to know where to save your script files, you need to navigate to the right folder before running a script, and later in this course you will write programs that read from and write to files, which require accurate file paths.

What a file path is

A path is the address of a file or folder on your computer. It describes where to find something by listing the folders you pass through to reach it.

Example 2.5.1
The same file addressed on two different operating systems
  • WindowsC:\Users\Alex\Documents\python_projects\hello.py
  • macOS / Linux/Users/alex/Documents/python_projects/hello.py
  • What it meansBoth paths describe the same logical location: a file called hello.py inside python_projects, which is inside Documents, which is inside the user's home folder. Windows uses backslash \ as a separator; macOS and Linux use forward slash /.

Two kinds of paths

Path TypeDescriptionExample (macOS/Linux)
Absolute path Gives the full address starting from the root of the file system. Always unambiguous. /Users/alex/python_projects/hello.py
Relative path Gives the address starting from the current working directory. Shorter and easier to read, but depends on where you are. hello.py (if you are already in python_projects)

Organizing your Python files

From the beginning of this course, create a clear folder structure for your work. Give your folders and files meaningful names. Use lowercase letters. Use underscores instead of spaces — spaces in folder names and file names can cause problems in the terminal.

Recommended folder structure for this course
python_projects/
    chapter_02/
        hello.py
        first_program.py
    chapter_03/
        variables.py
        expressions.py
    chapter_04/
        calculator.py
        converter.py
Sections 2.6 – 2.8
Working with Files: Creating, Running, and Organizing
Creating Scripts · Running Programs · File Organization

Creating a Python File

You create a Python file by opening your code editor, writing Python code, and saving the file with a .py extension. The steps differ slightly between editors, but the result is the same: a plain text file containing your Python source code.

Steps — IDLE
Creating a Python file in IDLE
  • Step 1Open IDLE. Go to File → New File. A blank editor window opens.
  • Step 2Type your Python code.
  • Step 3Go to File → Save As. Navigate to your chapter_02 folder. Type a file name ending in .py, for example hello.py. Click Save.
Steps — VS Code
Creating a Python file in Visual Studio Code
  • Step 1Open VS Code. Go to File → Open Folder and open your python_projects folder.
  • Step 2Click the New File icon in the Explorer panel on the left. Type a file name ending in .py. Press Enter. The new file opens.
  • Step 3Type your Python code. Save with File → Save or Ctrl+S (Windows) / Cmd+S (macOS).

Naming rules for Python files

File NameAssessmentReason
temperature_converter.py✓ GoodLowercase, underscores, descriptive, ends in .py
grade_checker.py✓ GoodClear and readable
my calculator.py✗ AvoidSpace in name causes terminal problems
hw3.py✗ AvoidNot descriptive — unclear months later
QuizProgram.py✗ AvoidMixed case is allowed but hard to type consistently
script.PY✗ AvoidUppercase extension; some systems may not recognize it

Running a Python Program

There are two main ways to run a Python program: from within your code editor, or from the terminal. Both ultimately do the same thing: they give your script file to the Python interpreter and display the output.

Running from the editor

In IDLE, open your .py file and press F5 or go to Run → Run Module. IDLE runs your program and shows output in the interactive shell window.

In Thonny, click the green play arrow or press F5. Output appears in the shell panel at the bottom.

In VS Code, click the play button in the top-right corner of the editor, or right-click inside the file and choose Run Python File in Terminal. VS Code opens a terminal panel and runs your script there.

Running from the terminal

This is the most general method. Open your terminal, navigate to the folder where your Python file is saved, and run the file:

Running a script from the terminal (macOS/Linux)
$ cd Documents/python_projects/chapter_02
$ python3 hello.py
Hello, world!
This is my first Python script.

The $ represents the terminal prompt — you do not type it. Everything after $ is what you type. The lines without $ are the output your program produced.

What happens step by step when Python executes a file

Execution trace
What Python does when you run python3 hello.py
  • Step 1The operating system finds the Python interpreter on your computer.
  • Step 2The interpreter opens and reads hello.py from disk.
  • Step 3The interpreter processes the file from the first line to the last, in order.
  • Step 4For each line, the interpreter carries out the instruction. If the line calls print(), the output appears in the terminal.
  • Step 5When the last line is reached, the program ends and the interpreter stops. The terminal returns you to its prompt.
  • On errorIf Python encounters a problem — a syntax error, a missing variable, a file that does not exist — it stops immediately, prints an error message, and returns you to the terminal prompt.
Never run scripts by double-clicking

On Windows, double-clicking a .py file opens a terminal window that closes as soon as the program finishes — often too fast to read. Always run scripts from inside your editor or from the terminal you already have open.

Saving, Naming, and Organizing Program Files

Good file organization becomes more important as your programs grow. Forming good habits early saves significant frustration later.

Save before every run

This sounds obvious, but beginners often forget to save after making changes. If you run an old saved version of a file, you will be confused when your latest edits do not appear in the output. Most code editors show a dot or asterisk in the file tab when there are unsaved changes. Watch for this indicator. In most editors, Ctrl+S (Windows) or Cmd+S (macOS) saves quickly.

Use descriptive file names

Your file name should give a clear idea of what the program does. Three months from now, grade_calculator.py will be much easier to find and understand than program3.py. Name files for what they do, not for when you wrote them.

One program per file

Each Python program should be its own file. Avoid putting two unrelated programs in the same file. This keeps things clear and makes running individual programs easy.

Folder structure and backups

Use folders organized by chapter or topic. For larger projects, give each project its own folder alongside its data files. Back up your work regularly — to a cloud service, a USB drive, or any second location. Programming coursework is difficult to recreate from memory.

Example project folder structure
python_projects/
    chapter_02/
        hello.py
        first_program.py
    quiz_program/
        quiz.py
        questions.txt
    gradebook/
        gradebook.py
        data.csv
Section 2.9
Common Setup Problems
Diagnose and Fix the Most Frequent Beginner Obstacles

Common Setup Problems

Setup problems are frustrating but very common. Nearly every programmer has spent time early on fighting installation and configuration issues. The problems below are the most frequently encountered ones, with step-by-step approaches for each.

Problem 1 "python is not recognized" or "command not found"
What it means: The terminal cannot find the Python interpreter. Python may not be installed, or it was installed but not added to the system's PATH.
  • Check that Python is installed. Look for Python in your applications list.
  • Try python3 instead of python.
  • On Windows: reinstall Python from python.org and check the box that says Add Python to PATH during installation. This checkbox is easy to miss.
  • On macOS: Python 2 may already be installed as python, but Python 3 is python3. Install Python 3 from python.org and use python3.
Problem 2 Python runs but the wrong version appears
What it means: You have multiple Python versions installed and the terminal is using an older one.
  • Use python3 explicitly instead of python.
  • Check the version with python3 --version.
Problem 3 "No such file or directory" when running a script
What it means: Python cannot find your script file. The terminal is looking in the wrong folder.
  • Check your current directory with pwd (macOS/Linux) or cd with no arguments (Windows).
  • Navigate to the folder that contains your script using cd.
  • Double-check the file name — it must match exactly, including the .py extension and capitalization.
  • Use ls (macOS/Linux) or dir (Windows) to confirm your file is in the current folder.
Problem 4 Script runs but prints nothing
What it means: The program ran successfully but produced no output, or the output went somewhere you did not expect.
  • Check that you used print() around everything you want to display. In a script, values do not print automatically the way they do in interactive mode.
  • Check that your print() calls are not inside an if block or loop that is never reached. (You will learn about these in later chapters.)
Problem 5 IndentationError
What it means: Python found code that is indented inconsistently. Python uses indentation to define code structure. Mixing tabs and spaces, or using wrong indentation amounts, causes this error.
  • Configure your editor to use four spaces for indentation. Do not mix tabs and spaces.
  • Look at the line number in the error message and check the indentation on that line and the lines around it.
Problem 6 SyntaxError
What it means: Python found something in your code that it could not understand because it violates the rules of Python syntax.
  • Look at the line number in the error message.
  • Common syntax errors include missing colons, unclosed parentheses, unmatched quotation marks, and misspelled keywords.
  • Compare your line to a working example. Even a single missing character can cause a SyntaxError.
How to read an error message

When Python encounters an error, it prints a message that almost always includes: (1) the file name where the error occurred, (2) the line number, and (3) a description of the problem. Read the error message before doing anything else. It is Python's attempt to help you find the problem. Even if the message is confusing at first, the line number alone will often point you directly to the issue.

Section 2.10
Your First Complete Program
print() · input() · Variables · Comments · Tracing

Your First Complete Program

Now you have enough background to write and run your first complete Python script. Work through this example carefully — read each line, predict what it does, then run it and verify your prediction. This habit of predicting before running is one of the most valuable you can build.

What this program does

The program below prints a short greeting, asks the user for their name, and then prints a personalized message. It uses two Python tools: print() to display output, and input() to receive text from the user. You will study both in depth in Chapter 4. For now, treat them as reliable tools you do not need to fully understand yet.

The program

Create a new file called first_program.py in your chapter_02 folder. Type this code exactly:

first_program.py
# My first Python program

print("Welcome to Python!")
print("Let's get to know each other.")

name = input("What is your name? ")

print("Hello,", name)
print("Nice to meet you.")

What to expect

Example 2.10.1
A sample run — user types "Alex" at the prompt
  • OutputWelcome to Python!
  • OutputLet's get to know each other.
  • PromptWhat is your name? — the program pauses and waits here.
  • User typesAlex then presses Enter.
  • OutputHello, Alex
  • OutputNice to meet you.

Reading the program line by line

Code Reading 2.10.1
What each line does
  • # My first…This is a comment. The # symbol tells Python to ignore everything on this line. Comments are notes for human readers — Python skips them entirely.
  • print(…)Calls the print() function with a string (a piece of text) inside the parentheses. Python displays the text in the terminal, followed by a new line.
  • name = input(…)Calls the input() function. The text inside the parentheses is displayed as a prompt. The program then waits for the user to type something and press Enter. Whatever they type is stored in the variable named name.
  • print("Hello,", name)Prints the word Hello, followed by the value stored in name. The comma inside print() places a space between the two pieces of output.
  • OverallThe program executes from top to bottom, one line at a time. Each instruction completes before the next begins. This top-to-bottom, line-by-line flow is the default execution order for every Python program.
Five ideas this small program demonstrates

1. Sequential execution. Programs run from top to bottom, one line at a time.

2. Output. print() sends text to the terminal.

3. Input. input() pauses and waits for the user to type something.

4. Variables. Variables store values that the program can use later. Here, name holds whatever the user typed.

5. Comments. Lines beginning with # are notes for humans. Python ignores them completely.

Experiments

After your program runs correctly, try these modifications one at a time. Run the program after each change to see what happens.

  • Add another print() line after the greeting with a message of your own.
  • Change the prompt text in input() to ask for something different.
  • Add this line at the end: print("Goodbye,", name)
  • Add a comment above each existing line explaining what it does.
  • Delete the # from the first comment line. Run the program. What happens? Why?

Chapter Summary

Key Terms

absolute path
A file path that gives the complete location starting from the root of the file system. Always unambiguous regardless of current directory.
code editor
A text editor designed for writing source code. Provides syntax highlighting, indentation help, and tools for running programs.
comment
A line in Python code beginning with # that Python ignores entirely. Used to leave explanatory notes for human readers.
current directory
The folder the terminal is currently working in. Also called the working directory. Relative paths are resolved from this location.
IDLE
The Integrated Development and Learning Environment bundled with Python. Includes an interactive shell and a simple file editor.
interactive mode
A mode where the Python interpreter reads and executes one line at a time, showing results immediately. Also called the Python shell or REPL.
interpreter
The program that reads Python source code and executes it. The bridge between what you write and what the computer does.
path
The address of a file or folder on the file system, describing where to find it by listing the folders you pass through.
primary prompt
The >>> symbol in Python's interactive shell, indicating the interpreter is waiting for input.
Python 3
The current, supported version of Python. Used throughout this textbook. Not fully compatible with the retired Python 2.
relative path
A file path that gives the location relative to the current working directory. Shorter than an absolute path but depends on where you are.
REPL
Read, Evaluate, Print, Loop. Another name for the Python interactive shell — it reads a line, evaluates it, prints the result, and loops back for more input.
script
A Python program stored as a .py file. Run by giving the file to the Python interpreter.
script mode
A mode where Python reads and executes an entire .py file from top to bottom. Output is shown only where print() is called.
source code
The human-readable text that a programmer writes. In Python, stored in .py files as plain text.
terminal
A text-based interface for communicating with the operating system using typed commands. Called Command Prompt or PowerShell on Windows, Terminal on macOS and Linux.

Setup Checklist

Work through this checklist before moving to Chapter 3. Every item here is a foundation for every chapter that follows.

Chapter 2 Setup Checklist
Complete every item before continuing to Chapter 3
Installation
  • Python 3 is installed on my computer.
  • I ran python3 --version in the terminal and saw a Python 3.x version number.
  • I have a code editor installed and open (IDLE, Thonny, or VS Code).
Interactive Mode
  • I opened the Python interactive shell.
  • I typed 2 + 2 at the >>> prompt and saw 4.
  • I typed a string like "hello" and saw it echoed back.
  • I can explain why typing a variable name in interactive mode shows its value, but not in a script.
Files and Folders
  • I created a python_projects folder with a chapter_02 subfolder.
  • I created first_program.py in my chapter_02 folder.
  • I can explain the difference between an absolute path and a relative path.
Running Programs
  • I ran first_program.py from inside my editor and saw the expected output.
  • I opened a terminal and navigated to my chapter_02 folder using cd.
  • I ran first_program.py from the terminal using python3 first_program.py.
  • I can explain what Python does step by step when it executes a script file.
Troubleshooting
  • I can describe what causes "python not recognized" and how to fix it.
  • I can describe what to do when a script produces no output.
  • I know how to read the line number from a Python error message.
Exercises File Path Practice

No programming required. These exercises build comfort with file paths and terminal navigation before you need them inside Python programs.

Use this folder structure for Exercises 1 and 2:

Reference folder structure
home/
    alex/
        python_projects/
            chapter_02/
                hello.py
                calculator.py
            chapter_03/
                variables.py
  1. Reading paths.
    a. What is the absolute path to hello.py? (Use macOS/Linux format with / separators.)
    b. If your current directory is chapter_02, what is the relative path to hello.py?
    c. If your current directory is python_projects, what is the relative path to variables.py?
    d. If your current directory is chapter_03, what is the relative path to hello.py?
    e. Write the cd commands to navigate from home/alex to chapter_02.
  2. Terminal commands. Without running anything, predict what the terminal would display for each command. Assume you start in the python_projects folder.
    a. ls (macOS/Linux) or dir (Windows)
    b. cd chapter_02, then ls
    c. cd .. (what folder are you in now?)
    d. pwd after cd chapter_02
  3. Naming decisions. Which of these file names follow good Python naming conventions? For those that do not, explain what is wrong.
    a. my calculator.py
    b. temperature_converter.py
    c. QuizProgram.py
    d. hw3.py
    e. grade_report_generator.py
    f. script.PY
Exercises Command and Program Practice
  1. Interactive shell exploration. Open the Python interactive shell. Type each of the following lines and record what Python shows. For each result, write one sentence explaining what you think Python did.
    >>> 10 + 5
    >>> 100 - 37
    >>> 4 * 8
    >>> 15 / 4
    >>> 15 // 4
    >>> 15 % 4
    >>> "hello"
    >>> "hello" + " " + "world"
    >>> type(42)
    >>> type("hello")
  2. Program A — Three print statements. Create and run a script that prints three things: your name, a city you would like to visit, and a number between 1 and 100 that you chose. Save it as three_things.py.
  3. Program B — Simple math output. Write a program that prints the results of three calculations with clear labels. For example: 144 / 12 = 12.0. The three calculations: 144 divided by 12; 17 multiplied by 6; 1000 minus 237. Save it as math_output.py.
  4. Program C — Greeting with two inputs. Starting from first_program.py, write a new program called greeting.py that asks for the user's name, then asks for the user's favorite color, then prints a message using both values.
Exercises Troubleshooting Scenarios

For each scenario, explain what likely went wrong and what steps you would take to fix it.

  1. You type python hello.py in the terminal and see:
    python: can't open file 'hello.py': [Errno 2] No such file or directory
  2. You run your script from IDLE and the output window appears but shows nothing. You expected to see three lines of text.
  3. You type python --version and see Python 2.7.18. You want to use Python 3.
  4. You double-click your .py file on Windows. A black window flashes briefly and disappears before you can read anything.
  5. You run a script and see this error message:
      File "hello.py", line 3
        print("Hello)
                    ^
    SyntaxError: EOL while scanning string literal
    What does this error mean? What is probably wrong on line 3?
  6. You run a script and see the output from the old version of your program, not your recent changes. What probably happened, and how do you prevent this?
Review Review Questions

Answer each question in complete sentences.

  1. What is the Python interpreter and what is its role? Why is it needed to run Python code?
  2. What is the difference between Python 2 and Python 3? Why does this textbook use Python 3?
  3. What is the difference between interactive mode and script mode? Give one situation where interactive mode is the better choice and one situation where script mode is the better choice.
  4. Why should you never write Python programs in Microsoft Word or another word processor?
  5. What does the # symbol do in a Python program? What would happen if you accidentally removed it from the beginning of a comment line?
  6. What does print() do? How is its behavior in a script file different from how values appear in the interactive shell?
  7. What does the .py extension in a file name indicate? What would happen if you saved a Python file as hello.txt?
  8. What is a file path? What is the difference between an absolute path and a relative path? When is a relative path more convenient?
  9. What does the cd command do in the terminal? What does cd .. do?
  10. Why should you always save your Python file before running it?
  11. When you run python3 hello.py in the terminal, describe what happens step by step from the moment you press Enter until the terminal prompt returns.
  12. Name three common setup problems beginners face. For each one, describe one likely cause and one step toward fixing it.
Preview — Chapter 3
Values, Variables, and Expressions

Chapter 2 gave you the tools to write and run Python programs. Chapter 3 teaches you what to put inside them. You will learn about the smallest building blocks of Python programs: values, variables, and expressions. You will see how Python stores and works with numbers and text, how to name variables clearly, how arithmetic operators work, and how to trace the way expressions are evaluated step by step. By the end of Chapter 3, you will be writing short programs that calculate results, store them in named variables, and display them using print(). The programs are still small — but the ideas behind them run through every program you will ever write.

MGU Library Connection
  • Appendix A: Installing and Running Python — full step-by-step installation guide
  • Appendix B: Command Line and File Paths Reference — complete terminal commands by operating system
  • Appendix D: Common Python Error Messages — quick reference for SyntaxError, IndentationError, and more
  • Companion resource: Python Installation Guide
  • Companion resource: Command Line Basics Guide
  • Companion resource: File Path Guide
  • Prerequisite: Computer Science Foundations — Chapter 3 (Programs as Instructions) provides relevant background