Python

General

Python is a programming language.

Modules are imported by scripts, while scripts which contains Python code are executed by an interpreter (like Python’s IDLE).

# Python Module example
# code below saved as addn.py
def add(a, b):   “””This program adds two   numbers and return the result”””
   result = a + b   return result
# Python Script example
# code below saved as toadd.py
# toadd.py to be run by cmd or IDLE
import addnaddn.add(4,5.5)
# Output9.5

Python in Shell

PATH is an environment variable in Windows. It basically tells the commandline what folders to look in when attempting to find a file. If you didn’t add Python to PATH then you would call it from the commandline like this:

C:/Python27/Python some_python_script.py

Whereas if you add it to PATH, you can do this:

python some_python_script.py
  • Open Shell
  • Enable Python environment (ensure Python installed beforehand): python
  • This will show up: >>>

Sample code with Python in Command Prompt:

>>> print(‘Hello World!’)
Hello World!
>>> 2 + 57

To exit Python environment: quit() or exit() or ctrl+z (and enter)

To run *.py (e.g. abc.py), 
Command Prompt
place file in directory
Exit Python environment (if in it)
Go to directory of abc.py
Type and press enter: python abc.py
IDLE
Open abc.py in IDLE
Run (press F5)

To find where python is installed, execute in cmd: where python

Python’s Packages

PIP

PIP is Python’s package manager.

# Check PIP version
PIP --version

# Download and install package like TensorFlow and camelcase
pip install packagename

# Using package
import camelcase

c = camelcase.CamelCase()

Package

h

# Useful packages list
pip install jupyterlab # jupyterlab; launch with: jupyter-lab
pip install notebook # classic Jupyter notebook; launch with: jupyter notebook
venv / pyvenvsingle Python version
pyenvmultiple Python version (deprecated @ Python 3.8+ and replaced with venv)
pyenv-virtualenvPython 2 inclusive

venv

$ python3 -m venv directory-name-to-create
# e.g. python3.6 -m venv example-three-six
$ source name-given/bin/activate
$ deactivate
$ rm -r name-given

When the environment is active, any packages can be installed to it via pip as normal (by default, the newly created environment will not include any packages).

Check python version: python –version


Reference

  1. Real Python. (2021, June 21). How to Run Your Python Scripts. Retrieved August 22, 2021, from https://realpython.com/run-python-scripts/
  2. TrajanTrajan 1, et al. “Why Would I Add Python to PATH.” Stack Overflow, 1 June 1964, stackoverflow.com/questions/34900042/why-would-i-add-python-to-path.