smartyfy.mrindigi.com

Python Master Course V2 — 002. Installing Python & Setting Up the Environment

Module 01 · Python foundations · Lesson 002 / 200

Installing Python & Setting Up the Environment

In this lesson · 13 sections + self-check
  1. Watch: Installing Python & Setting Up the Environment
  2. 01 — What you will achieve
  3. 02 — Know your tools before you install anything
  4. 03 — Install Python securely: choose your operating system
  5. 04 — Verify the interpreter, not just the installation
  6. 05 — Configure a professional editor and run your first script
  7. 06 — Virtual environments: one project, isolated dependencies
  8. 07 — Installing packages correctly with pip
  9. 08 — A repeatable project workflow used in real development
  10. 09 — Troubleshooting like a professional
  11. 10 — Guided laboratory: build a working Python workspace
  12. 11 — Knowledge check and mastery review
  13. 12 — Summary, best practices & next steps
  14. Interactive self-check

🎬 VIDEO LESSON

Watch: Installing Python & Setting Up the Environment

Video coming soon

Reserved for the Lesson 002 video player or video link.

Video URL: [ADD LESSON 002 VIDEO URL HERE]

Editors: replace this placeholder with a YouTube/Vimeo embed or a self-hosted video link when the recording is available. No video URL has been invented.

01 — What you will achieve

By the end of this lesson you should be able to do more than “install an application.” You should know which Python executable runs your code, where packages are installed, and how to set up a project so its dependencies do not unexpectedly affect another project.

Your outcomes
  • Install Python from a trustworthy source.
  • Open a terminal and check Python’s version.
  • Create and run a .py file.
  • Select the correct interpreter in an editor.
  • Create a project-local virtual environment.
  • Use python -m pip intentionally.
  • Troubleshoot PATH, permissions, and interpreter mismatches.
Prerequisites & materials
  • Completion of Lesson 001, or basic programming familiarity.
  • A Windows, macOS, or Linux computer.
  • Internet access for downloading Python and an editor.
  • Permission to install software or an approved organization-managed installation.
  • No previous coding experience required.

Success criterion: you can run hello.py from your project’s virtual environment and independently confirm the exact Python executable that ran it.

02 — Know your tools before you install anything

Python the language vs. the interpreter

Python is a programming language. An interpreter/runtime is installed software that runs code written in that language. A script is a text file containing Python instructions, usually with a .py extension. An editor is where you write and inspect those instructions. A terminal is a text-based interface used to launch programs and issue commands.

You write code in an editor
          ↓
      hello.py
          ↓
Terminal asks the selected Python runtime to execute it
          ↓
Python processes the instructions
          ↓
       Output / errors

There may be multiple Python interpreters on one computer. Some come from an official installer, others from operating-system tools, scientific distributions, IDEs, or virtual environments. This explains why merely typing “Python works” is not sufficient for a reliable development setup: you also need to know which Python works.

Three related but different commands

  • python, python3, and on many Windows machines py may select a Python installation, but availability differs by operating system and setup.
  • pip installs Python packages, but calling it by itself may target a different interpreter from the one you intend to use.
  • python -m pip tells that specific Python interpreter to run its pip module, which is generally safer than an unqualified pip.

In the following sections, commands beginning with py are Windows examples where the Python launcher is available. Commands beginning with python3 are common on macOS/Linux. Once a project environment is activated, the command python will normally resolve to its interpreter.

03 — Install Python securely: choose your operating system

For a general-purpose learning installation, use the official Python download site: python.org/downloads. Choose a supported stable Python 3 release suitable for your platform, and use the instructions associated with that release. Installer screens may differ by version and operating system. Avoid unverified third-party download sites and opaque “one-command installers.”

Windows: step by step

  1. Check whether Python 3 is already installed by opening PowerShell or Command Prompt and entering py -3 --version, or python --version if the launcher is unavailable.
  2. If it is not installed or you need a supported release, download the appropriate Windows installation option from Python.org. Follow the current official installer directions.
  3. If your installer provides a clearly labeled Add Python to PATH option, understand that selecting it allows commands such as python to be found in a new terminal. Some installation methods configure commands differently.
  4. Complete installation and close/reopen the terminal so environment changes are picked up.
  5. Verify with py -3 --version or python --version. Record which command works.
py -3 --version
py -3 -m pip --version

The py launcher is not guaranteed to exist on every Windows setup. If unavailable, use the verified python executable instead.

macOS: step by step

  1. Open Terminal and test python3 --version.
  2. If needed, obtain a supported Python 3 installer from Python.org and follow its current macOS instructions. An organization-managed installation or trusted package manager may be appropriate where permitted.
  3. Open a new terminal, then confirm the version and executable location.
  4. Use python3 explicitly until the project-local environment is active; the unqualified python command may be absent or refer to something different.
python3 --version
command -v python3
python3 -m pip --version

Linux: step by step

  1. Open your terminal and check python3 --version; many distributions already include Python for system tools.
  2. If Python or its virtual-environment support is missing, use your distribution’s package manager and recommended packages.
  3. On Debian/Ubuntu-based systems, typical packages include python3, python3-venv, and python3-pip.
  4. Verify the installation and keep project dependencies out of the system-managed Python environment.
python3 --version
command -v python3

# Debian/Ubuntu example, if packages are missing:
sudo apt update
sudo apt install python3 python3-venv python3-pip

Package names and policies differ across Linux distributions. Do not use sudo pip install to place course packages into your system interpreter.

04 — Verify the interpreter, not just the installation

Start with a version check. Then inspect the executable path used by the interpreter. This distinction prevents subtle bugs where you install a package into one Python but run your code using a different Python.

Windows (launcher present):

py -3 --version
py -3 -c "import sys; print(sys.executable)"

macOS / Linux:

python3 --version
python3 -c "import sys; print(sys.executable)"

-c executes the quoted Python expression directly without needing a script file. The sys.executable property reports the path of the running Python program. Its exact output is computer-specific; do not try to match an example path character for character.

Interpreter vs. terminal commands

A common early mistake is typing print("Hi") into PowerShell or a regular terminal as though it were already inside Python. It is Python code, not a universal shell command. You can enter a Python interactive session by running your Python command by itself (for example python3), then type Python code at the >>> prompt. Leave interactive mode by typing exit(). Alternatively, write code in a .py file and execute it from the terminal.

05 — Configure a professional editor and run your first script

Plain-text editors can write Python, but a modern code editor reduces unnecessary work by offering syntax highlighting, indentation assistance, search, terminal integration, debugging tools and interpreter selection. One widely used choice is Visual Studio Code; another acceptable choice is a Python-focused IDE. This lesson uses VS Code as an example, but the terminal workflow applies to other editors.

  1. Install your chosen editor from its official publisher.
  2. Open a dedicated folder for the course, such as python-master-course, rather than saving every script on the desktop.
  3. If using VS Code, install the Python extension from Microsoft in the editor’s extensions marketplace.
  4. Use the command palette action Python: Select Interpreter and choose the interpreter you verified. We will change it to the project’s virtual environment shortly.
  5. Create a file named hello.py and save it as ordinary UTF-8 text. Ensure the name does not become hello.py.txt.

Example 1 — Hello, Python

# hello.py
print("Hello, Smartyfy!")
print("My Python environment is working.")

From the folder containing hello.py, run python hello.py, python3 hello.py, or py -3 hello.py, using the command that works on your platform. Expected output:

Hello, Smartyfy!
My Python environment is working.

Example 2 — A small calculation

# budget.py
item_price = 375
quantity = 4
total = item_price * quantity

print("Price:", item_price)
print("Quantity:", quantity)
print("Total:", total)

The calculation produces Total: 1500. You have now run a script that performs actual processing rather than only printing fixed text.

Professional habit: always read the terminal output. Confirm that a script really ran and produced the result you predicted. A successful editor installation does not guarantee that the editor is using the intended interpreter.

06 — Virtual environments: one project, isolated dependencies

Imagine two projects: one is tested with a particular library version, while another needs a different version. Installing every dependency globally can create conflicts. A virtual environment gives each project a separate Python environment and package installation location. The standard-library venv module is a good place to start.

A virtual environment does not create an entirely separate operating system or isolate programs as strongly as a virtual machine or container. It mainly gives the project its own interpreter entry point and isolated installed Python packages.

Create a project folder

In the terminal, navigate to the directory where you keep projects. Create a new project folder and enter it:

mkdir smartyfy-python-lab
cd smartyfy-python-lab

Create the environment

Windows:

py -3 -m venv .venv

macOS / Linux:

python3 -m venv .venv

If Windows does not have py, use your verified python -m venv .venv instead. The folder name .venv is a widespread convention, not a mandatory special word.

Activate the environment

ShellActivation command
Windows PowerShell.\.venv\Scripts\Activate.ps1
Windows Command Prompt.venv\Scripts\activate.bat
macOS / Linux shellsource .venv/bin/activate

Many terminals show (.venv) in the prompt after activation. Confirm more reliably with:

python -c "import sys; print(sys.executable)"

The printed path should point into the project’s .venv folder. On Windows, interpreter paths use backslashes; on macOS/Linux, forward slashes.

If activation is blocked

Windows PowerShell execution policy can restrict script activation. You do not need to weaken a machine-wide security policy for this lesson. Use Command Prompt activation, or call the environment interpreter directly:

# Windows, without activation:
.venv\Scripts\python.exe hello.py

# macOS/Linux, without activation:
.venv/bin/python hello.py

The script must exist in the location referenced by the command. Activation is only a convenience for selecting the project’s executables; it is not technically required.

Leave the environment

Use deactivate after activation to restore your previous shell environment. Re-activate the project when you return to work.

07 — Installing packages correctly with pip

Python includes a substantial standard library, but many projects also use external packages. The Python Package Index (PyPI) is a common source. Install only packages you trust and actually need, preferably inside a project-local virtual environment.

After activating .venv, first inspect pip:

python -m pip --version
python -m pip list

To install an external HTTP library as a demonstration (requires internet):

python -m pip install requests
python -m pip show requests

We do not need this package for Lesson 002, so you can skip installation if you are offline. If you install it, verify with:

python -c "import requests; print(requests.__version__)"

You can capture installed versions into a requirements file with:

python -m pip freeze > requirements.txt

On another installation of the same project, dependencies can be installed with python -m pip install -r requirements.txt. Note that a pip freeze file is a snapshot of installed packages, not necessarily a fully curated production dependency strategy. In future lessons we will learn better dependency management, testing, and reproducible builds.

Remember: prefer python -m pip ... from inside the chosen environment. This binds package operations to the Python you intend to run.

08 — A repeatable project workflow used in real development

Projects become much easier to maintain when files and dependencies have predictable locations. Use a simple structure:

smartyfy-python-lab/
├── .venv/                 # Local environment: do not commit
├── hello.py               # A small introductory script
├── environment_report.py  # Setup diagnostic program
├── requirements.txt       # Dependency snapshot (optional)
└── .gitignore             # Exclusions for version control

A typical .gitignore starts with:

.venv/
__pycache__/
*.pyc
.env

The .env entry helps avoid accidentally committing local secrets stored in such files, but the exclusion alone is not a complete secrets-management policy.

Example 3 — Write an environment report

Create a file named environment_report.py in your project folder. This example uses only standard-library modules; it works without extra packages:

"""Show which Python environment runs this project."""

import platform
import sys
from pathlib import Path

print("=== SMARTYFY PYTHON ENVIRONMENT REPORT ===")
print("Python version:", platform.python_version())
print("Platform:", platform.system())
print("Interpreter:", sys.executable)
print("Working directory:", Path.cwd())
print("Virtual environment active:", sys.prefix != sys.base_prefix)

Run it with python environment_report.py after activating the virtual environment. This is a practical diagnostic, not merely a classroom demonstration.

Why the last line works: in the standard venv case, sys.prefix represents the active environment while sys.base_prefix refers to the base installation. When they differ, the program is generally running under a virtual environment. More complicated interpreter setups may behave differently, so interpret diagnostics in context.

Example 4 — Produce a useful local report

This second program takes information from the runtime and writes a text report into the current project directory.

from datetime import datetime
from pathlib import Path
import platform
import sys

report_lines = [
    "SMARTYFY ENVIRONMENT CHECK",
    f"Generated: {datetime.now().isoformat(timespec='seconds')}",
    f"Python: {platform.python_version()}",
    f"Interpreter: {sys.executable}",
    f"OS: {platform.system()}",
]
report_path = Path("setup_report.txt")
report_path.write_text("\n".join(report_lines) + "\n", encoding="utf-8")

print(f"Report saved: {report_path.resolve()}")

The new setup_report.txt file contains the details you need when asking for help with environment-specific errors. Open it with your editor and inspect it. Note that this text report contains a local path; remove any personally sensitive path details before sharing screenshots or logs publicly.

A practical success checklist

  • The command-line Python interpreter runs and reports a version.
  • The editor opens your project folder, not an unrelated folder.
  • You can execute hello.py from the terminal.
  • You have created .venv successfully.
  • sys.executable points inside .venv when using the project environment.
  • The report program runs without an additional dependency.

09 — Troubleshooting like a professional

SymptomLikely causeSafe next step
python not foundNot installed, command not on PATH, or different launch commandTry verified py -3 on Windows or python3 on macOS/Linux; reopen the terminal.
Wrong Python versionMultiple interpreters installedPrint sys.executable and explicitly select the correct interpreter.
No module named ...Package missing from the interpreter running the scriptCheck sys.executable; run python -m pip show PACKAGE in the same environment.
can't open fileIncorrect path or working directoryCheck current directory, file spelling and extension; run the file by its actual path.
PowerShell activation deniedScript execution restrictionsUse Command Prompt activation or call .venv\Scripts\python.exe directly.
Editor and terminal behave differentlyEditor selected another interpreterUse the editor’s interpreter selector; compare sys.executable from both.
Linux package install blockedOS-managed Python environmentCreate venv with the distribution’s supported Python packages; avoid overriding system protection.

A five-step diagnostic method

  1. Copy the exact error text (without secrets).
  2. Record the command you executed and the folder you were in.
  3. Check sys.executable and Python version.
  4. Identify whether the failure occurs during installation, import, editing, or execution.
  5. Make one change at a time and rerun the same check.

Randomly reinstalling packages, changing system PATH repeatedly, or copying unreviewed commands often creates more problems than it solves. A small written diagnostic log makes recovery faster.

10 — Guided laboratory: build a working Python workspace

Scenario: you have joined a team that will soon automate CSV reports. Before writing that application, you must provide evidence that your development machine can run Python in an isolated project and generate a useful environment report.

Part A — Guided steps

  1. Create smartyfy-python-lab and open the folder in your editor.
  2. Create .venv using the correct platform command.
  3. Activate the environment, or use its interpreter directly.
  4. Create hello.py with two print() calls.
  5. Create environment_report.py using Example 3 above.
  6. Run both scripts. Inspect the interpreter path in the report.
  7. Run Example 4 as a separate script named save_report.py and confirm the report file appears.
  8. Write one paragraph explaining why the local environment is useful.

Part B — Independent exercises

  1. Change the greeting script to print your learning goal and the current lesson number.
  2. Use Path.cwd() to display the current folder. Run the program from a different folder and explain the change.
  3. Print the first three elements of sys.version_info and explain what they represent.
  4. Temporarily deactivate your environment and compare sys.executable before and after activation.
  5. Create a Markdown file README.md explaining your setup commands in your own words.
  6. Explain why copying another learner’s virtual-environment folder is less reliable than creating your own environment and installing declared dependencies.

Challenge — Create a setup health-check tool

Write health_check.py that displays a useful success/failure report for your Python development environment. It should check the Python version, interpreter path, current directory, and whether you are in a virtual environment. For stretch credit, check that the working directory contains hello.py using Path("hello.py").is_file(), and print a meaningful message when it is missing. Do not modify your system configuration automatically.

Acceptance criteria: the tool runs without third-party packages; reports interpreter and platform; clearly states whether a standard virtual environment is active; and uses human-readable labels. Save its output and describe one improvement you would make for a team environment.

Optional reference solution

Reveal a sample health-check implementation (try first)
import platform
import sys
from pathlib import Path

project = Path.cwd()
is_venv = sys.prefix != sys.base_prefix

print("PYTHON SETUP HEALTH CHECK")
print("-" * 28)
print(f"Python: {platform.python_version()}")
print(f"OS: {platform.system()}")
print(f"Interpreter: {sys.executable}")
print(f"Project folder: {project}")
print(f"Virtual environment: {'YES' if is_venv else 'NO'}")

if Path("hello.py").is_file():
    print("hello.py: FOUND")
else:
    print("hello.py: NOT FOUND in current folder")

if not is_venv:
    print("Tip: activate your project .venv environment.")

Instructor note: sys.prefix != sys.base_prefix is useful for normal standard-library venvs; alternative environment management systems may require additional checks.

11 — Knowledge check and mastery review

1. What is the difference between a Python script and the Python interpreter?

Hint

Distinguish the file from the program that reads it.

Show answer and explanation

A script is a text file containing Python instructions, usually ending in .py. The interpreter is the executable that reads and runs those instructions. Opening a script in an editor does not run it.

2. Why might python -m pip install ... be preferable to a plain pip install ... command?

Hint

Compare the interpreter used by pip with the one used by your script.

Show answer and explanation

python -m pip runs pip through that particular Python interpreter. This reduces the risk of installing into a different Python version or environment. Confirm sys.executable and the editor’s selected interpreter when an import cannot be found.

3. What does a virtual environment isolate, and what does it not fully isolate?

Hint

Think about Python packages versus the whole computer.

Show answer and explanation

A standard venv keeps project package installations and interpreter entry points separate from other projects. It is not a security sandbox, separate operating system, or independent copy of every resource; code still has the process’s normal filesystem and network permissions.

4. If the terminal runs code but your editor reports missing imports, what should you check first?

Hint

Two tools can select different Python executables.

Show answer and explanation

Compare the editor’s selected interpreter with the terminal’s sys.executable. Select the project .venv interpreter in the editor, then confirm that the package is installed using that same interpreter.

5. What does sys.executable tell you?

Hint

It is a path, not just a version number.

Show answer and explanation

sys.executable identifies the executable running the current Python process. It helps distinguish system Python, a virtual environment, and the browser runner. A matching version alone does not prove two tools use the same environment.

6. Can you use a virtual environment without activating it? Explain.

Hint

Activation changes command lookup; it is not required to run the executable.

Show answer and explanation

Yes. From the project folder, run .venv\Scripts\python.exe hello.py on Windows or .venv/bin/python hello.py on macOS/Linux. Activation makes short commands select that executable more conveniently.

7. Why is it unwise to install arbitrary course packages globally using sudo pip?

Hint

Consider packages managed by the operating system.

Show answer and explanation

Global elevated installs may conflict with system-managed packages and other projects. Create the project venv and install its declared dependencies through its interpreter. Administrative privileges are unnecessary for ordinary project dependencies.

8. What is the purpose of requirements.txt in this lesson?

Hint

It helps another person rebuild the dependencies.

Show answer and explanation

A requirements file lists dependencies for pip to install. A freeze snapshot may include transitive packages; a project’s deliberate dependency specification expresses its needs. The file does not capture the whole OS, credentials, or all compatibility assumptions.

9. What is the difference between a terminal error caused by a wrong file path and one caused by a missing module?

Hint

Did Python locate the script before trying imports?

Show answer and explanation

A wrong-path error such as “can’t open file” means the requested script was not located at that path. ModuleNotFoundError means execution reached an import that the selected interpreter cannot resolve. Check the current directory and filename for the first, then interpreter and installed packages for the second.

10. What four or five facts would you collect before asking for environment troubleshooting help?

Hint

Collect reproducible evidence rather than “it does not work”.

Show answer and explanation

Collect the exact command and complete error text, current working directory, Python version, executable path, and relevant package status. Also state the operating system and editor interpreter. These facts let someone reproduce the failure and identify a mismatched environment.

12 — Summary, best practices & next steps

You have learned to install Python responsibly, identify the actual runtime, create scripts, configure a development editor, isolate packages with venv, work with python -m pip, and troubleshoot problems systematically. Your setup is now ready for progressively more substantial Python programs.

Carry into Lesson 003

Keep your project folder and .venv. We will use this environment to write and run progressively more sophisticated programs.

Golden rule

When Python behaves unexpectedly, verify sys.executable before installing or reinstalling anything.

Further official references: Python setup and usage · venv documentation · Python Packaging User Guide · VS Code Python documentation.

SMARTYFY • Python Master Course V2 • Lesson 002 of 200 • Course content only; existing legacy lessons remain unchanged.

Apply what you learned

Interactive self-check

Choose an answer for each question, then check your work. You will see the correct answer and why it is correct.

1. How should you verify an installation?
2. Why create a virtual environment?
3. Which command targets pip for the selected interpreter?
4. Where do you usually run python hello.py?
5. An installed package cannot be imported. What should you check first?

This is a practice quiz. Results are saved on this browser when storage is available.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion and quiz results are stored on this browser.