Chapter 1 Python Environment Setup

Introduction

Python is a high-level programming language renowned for its simple and readable syntax and powerful libraries. Whether you’re a beginner or an experienced developer, Python is an excellent choice. This chapter will detail how to install and configure the Python environment on different operating systems, helping you quickly start your Python programming journey.

Example source code used in this series: Python From Beginner to Master Example Code

1.1 Python Installation and Configuration

Installation on Windows

  1. Visit the Python official website at https://www.python.org/downloads/ to download the latest Python installer.

  2. After downloading, double-click the installer to start the installation. Important note: Check the “Add Python to PATH” option at the bottom of the installation interface to automatically configure environment variables.

  3. Choose “Install Now” for a standard installation or “Customize installation” for a custom setup. The standard installation is recommended.

  4. After installation, open the Command Prompt (Win+R, type cmd) and enter the following command to verify the installation:

python --version

If the Python version number is displayed, the installation was successful.

Installation on macOS

  1. Using the official installer:
    - Visit https://www.python.org/downloads/mac-osx/ to download the macOS version of the Python installer
    - Double-click the .pkg file to start the installation
    - Follow the installation wizard to complete the installation

  2. Using Homebrew (recommended):

# First install Homebrew if not already installed
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Python using Homebrew
brew install python
  1. Verify the installation:
python3 --version

Installation on Linux

Most Linux distributions come pre-installed with Python, but it may not be the latest version. Here are methods to install Python on different Linux distributions:

Ubuntu/Debian systems:

# Update package list
sudo apt update

# Install Python 3
sudo apt install python3 python3-pip

# Verify installation
python3 --version

CentOS/RHEL systems:

# Install Python 3
sudo yum install python3 python3-pip

# Or use dnf for newer versions
sudo dnf install python3 python3-pip

Environment Variable Configuration

Windows system:
If you didn’t check “Add Python to PATH” during installation, manually configure it:
1. Right-click “This PC” → “Properties” → “Advanced System Settings” → “Environment Variables”
2. In “System Variables”, find “Path” and click “Edit”
3. Add the Python installation path (usually C:\Python311\) and the Scripts path (C:\Python311\Scripts\)

macOS/Linux systems:
Add the following to your ~/.bashrc or ~/.zshrc file:

export PATH="/usr/local/bin/python3:$PATH"

Then execute:

source ~/.bashrc  # or source ~/.zshrc

Verify Installation Success

Open the terminal or command prompt and execute the following commands:

# Check Python version
python --version
# or
python3 --version

# Check pip version
pip --version
# or
pip3 --version

# Enter Python interactive environment
python

If the version information is displayed correctly and you can enter the Python interactive environment, the installation was successful.

1.2 First Python Program

Hello World Program

Create a file named hello.py and enter the following code:

# This is my first Python program
print("Hello, World!")
print("Welcome to the world of Python!")

# Get user input
name = input("Please enter your name: ")
print(f"Hello, {name}!")

Running the Program

Command Line Execution

Open the terminal or command prompt, navigate to the file directory, and execute:

python hello.py

Running in IDE

In the PyCharm IDE, you can directly click the run button or use the shortcut key (usually Ctrl+F10) to run the program.

Interactive Execution

In the Python interactive environment, you can enter the code line by line:

>>> print("Hello, World!")
Hello, World!
>>> name = "Zhang San"
>>> print(f"Hello, {name}!")
Hello, Zhang San!

Program Structure Analysis

# 1. Comment: Starts with #, used to explain code
# This is my first Python program

# 2. Function call: print() is a built-in function for output
print("Hello, World!")

# 3. Variable assignment: Store user input in a variable
name = input("Please enter your name: ")

# 4. String formatting: Use f-string for formatted output
print(f"Hello, {name}!")

Common Errors and Solutions

Syntax error example:

# Error: Missing quotes
print(Hello, World!)
# SyntaxError: invalid syntax

# Correct:
print("Hello, World!")

Indentation error example:

# Error: Unnecessary indentation
    print("Hello, World!")
# IndentationError: unexpected indent

# Correct:
print("Hello, World!")

Name error example:

# Error: Using undefined variable
print(name)
# NameError: name 'name' is not defined

# Correct: Define before use
name = "Zhang San"
print(name)

1.3 Python Interactive Environment

Using Python Interpreter

The Python interpreter is the program that executes Python code. Enter python in the command line to start it:

$ python
Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Interactive Command Line (REPL)

REPL (Read-Eval-Print Loop) is Python’s interactive environment that executes code immediately and displays results:

>>> 2 + 3
5
>>> name = "Python"
>>> print(f"I'm learning {name}")
I'm learning Python
>>> import math
>>> math.pi
3.141592653589793

Common REPL commands:
- help(): Get help information
- exit() or quit(): Exit REPL
- dir(): View objects in the current namespace
- _: Get the result of the last expression

Installation and Use of IPython

IPython is an enhanced Python interactive environment with more features:

# Install IPython
pip install ipython

# Launch IPython
ipython

IPython features:
- Syntax highlighting: Automatic code coloring
- Autocompletion: Press Tab to autocomplete
- Magic commands: Special commands starting with %
- History: Easy to view and reuse previous commands

In [1]: import os

In [2]: os.getcwd()  # Press Tab for autocompletion
Out[2]: 'C:\\Users\\username'

In [3]: %pwd  # Magic command to show current directory
Out[3]: 'C:\\Users\\username'

In [4]: %history  # Show command history

Introduction to Jupyter Notebook

Jupyter Notebook is a web-based interactive development environment, ideal for data analysis and machine learning:

# Install Jupyter
pip install jupyter

# Launch Jupyter Notebook
jupyter notebook

After launching, a Jupyter interface will open in your browser, where you can create new notebook files (.ipynb).

Advantages of Jupyter:
- Mixed code and documentation writing
- Supports Markdown-formatted documents
- Visual results displayed directly
- Supports multiple programming languages
- Easy to share and collaborate

Advantages of Interactive Environments

  1. Immediate feedback: See code execution results immediately
  2. Quick testing: Verify the correctness of code snippets
  3. Learning tool: Explore Python functions and libraries
  4. Debugging aid: Check variable values and program state
  5. Prototype development: Rapidly build program prototypes

1.4 Using Package Management Tool pip

Introduction to pip

pip (Pip Installs Packages) is Python’s standard package management tool for installing and managing Python packages. Since Python 3.4, pip has been built into the Python installation.

# Check pip version
pip --version

# Upgrade pip to the latest version
python -m pip install --upgrade pip

Installing and Uninstalling Packages

pip install command

# Install the latest version of a package
pip install requests

# Install a specific version of a package
pip install requests==2.28.1

# Install packages within a version range
pip install "requests>=2.25.0,<3.0.0"

# Install from requirements.txt file
pip install -r requirements.txt

# Install a local package
pip install ./my_package

# Install from a Git repository
pip install git+https://github.com/user/repo.git

pip uninstall command

# Uninstall a package
pip uninstall requests

# Uninstall multiple packages
pip uninstall requests urllib3 certifi

# Batch uninstall from a file
pip uninstall -r requirements.txt

Upgrading and Downgrading Packages

# Upgrade a package to the latest version
pip install --upgrade requests

# View outdated packages
pip list --outdated

# Downgrade to a specific version
pip install requests==2.25.1

Using requirements.txt File

The requirements.txt file records project dependencies and their versions:

# Example requirements.txt
requests==2.28.1
numpy>=1.21.0
pandas~=1.4.0
matplotlib
flask==2.2.2

Generate requirements.txt:

# Export all packages in the current environment
pip freeze > requirements.txt

# Only export packages actually used in the project (requires pipreqs)
pip install pipreqs
pipreqs . --encoding=utf8

Using requirements.txt:

# Install all dependencies
pip install -r requirements.txt

# Upgrade all dependencies
pip install -r requirements.txt --upgrade

Configuring Domestic Mirror Sources

Due to network restrictions, using domestic mirror sources can significantly improve download speeds:

Temporarily use a mirror source:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ requests

Permanently configure a mirror source:

Create a pip configuration file in your user directory:
- Windows: %APPDATA%\pip\pip.ini
- macOS/Linux: ~/.pip/pip.conf

Configuration file content:

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple/
trusted-host = pypi.tuna.tsinghua.edu.cn

Common domestic mirror sources:
- Tsinghua University: https://pypi.tuna.tsinghua.edu.cn/simple/
- Aliyun: https://mirrors.aliyun.com/pypi/simple/
- University of Science and Technology of China: https://pypi.mirrors.ustc.edu.cn/simple/
- Douban: https://pypi.douban.com/simple/

Introduction to Virtual Environments

Virtual environments create isolated Python environments for different projects to avoid package version conflicts:

# Create a virtual environment
python -m venv myproject_env

# Activate the virtual environment
# Windows:
myproject_env\Scripts\activate
# macOS/Linux:
source myproject_env/bin/activate

# Install packages in the virtual environment
pip install requests

# Exit the virtual environment
deactivate

Advantages of virtual environments:
- Isolated project dependencies
- Avoid version conflicts
- Facilitate project deployment
- Keep the system environment clean

Summary of Common pip Commands

# List installed packages
pip list

# Show detailed information about a package
pip show requests

# Search for packages (note: PyPI has disabled search functionality)
pip search keyword

# Check package dependencies
pip check

# Download packages without installing
pip download requests

# View pip configuration
pip config list

# Clear pip cache
pip cache purge

After learning this chapter, you’ve mastered Python environment setup and basic usage. Next, you can start learning Python’s basic syntax and begin your Python programming journey!

Xiaoye