Installing Python
Why Setup Matters
A proper Python setup is the foundation for all Python development. Without it, you'll run into dependency conflicts, version issues, and frustrating debugging sessions.
Installing on Different Platforms
Windows:
- Download from python.org
- Run the installer with "Add Python to PATH" checked
- Verify installation:
python --version
# Python 3.12.0
pip --version
# pip 23.3.1 from ... (python 3.12)
macOS:
# Using Homebrew (recommended)
brew install python@3.12
# Verify
python3 --version
Linux (Ubuntu/Debian):
sudo apt update
sudo apt install python3.12 python3.12-venv
# Verify
python3 --version
Common Installation Issues
| Issue | Solution |
|---|---|
python not found |
Use python3 or add to PATH |
pip not found |
Run python -m ensurepip |
| Permission denied | Use --user flag or virtual env |
| Multiple versions | Use py -3.12 on Windows |
Virtual Environments
Why Virtual Environments?
Virtual environments isolate project dependencies. Without them:
- Project A needs
requests==2.28 - Project B needs
requests==2.31 - Conflict!
Creating Virtual Environments
# Create a virtual environment
python -m venv myenv
# Activate it
# Windows
myenv\Scripts\activate
# macOS/Linux
source myenv/bin/activate
# You'll see (myenv) in your prompt
(myenv) $
Managing Dependencies
# Install packages
pip install requests flask
# Save dependencies
pip freeze > requirements.txt
# Install from requirements.txt
pip install -r requirements.txt
# Deactivate when done
deactivate
Best Practices
- Always use virtual environments - never install globally
- Add
.envto.gitignore- never commit virtual environments - Use
requirements.txt- document your dependencies - Name environments clearly -
myenvis not descriptive
Modern Alternatives
# Using poetry (modern dependency management)
poetry new myproject
cd myproject
poetry add requests
# Using pipenv
pipenv install requests
Running Python Code
Interactive Mode (REPL)
$ python3
>>> 2 + 2
4
>>> print('Hello, World!')
Hello, World!
>>> exit()
Use the REPL for:
- Quick experiments
- Testing small code snippets
- Learning new features
Running Scripts
# hello.py
def greet(name):
return f'Hello, {name}!'
if __name__ == '__main__':
print(greet('World'))
$ python hello.py
Hello, World!
The if __name__ == '__main__' Pattern
This pattern ensures code runs only when executed directly (not when imported):
# utils.py
def add(a, b):
return a + b
# This only runs when utils.py is executed directly
if __name__ == '__main__':
print(add(2, 3)) # 5
Running Python One-Liners
# Using -c flag
$ python -c "print('Hello')"
Hello
# Using python -m to run modules
$ python -m http.server 8000
# Starts a simple HTTP server
IDE Setup
VS Code:
- Install Python extension
- Select Python interpreter
- Use built-in terminal
PyCharm:
- Create new project
- Auto-detects virtual environment
- Full debugging support