Source
Adapted from my own handwritten and hand-typed notes from Year 1 to Year 3 of my EEE degree
Python is an open source, general purpose programming language built by Guido van Rossum in 1991. It is popular because the code is human readable and it has a huge set of third-party packages (pandas, numpy, matplotlib for handling and plotting data).
Compiled vs Interpreted
| C | Python | |
|---|---|---|
| How it runs | Source *.c is compiled to machine code *.o, then executed | Source *.py is interpreted and run directly |
| Speed | Faster execution | Slower execution |
| Flexibility | Strict structure | Flexible and interactive |
| Style | Procedure oriented (POP) | Object oriented (OOP) |
Python still compiles source to bytecode (*.pyc) behind the scenes, but no explicit compile step is needed.
Procedure vs Object Oriented
Two styles of programming:
- POP (C): a sequence of procedures that get a task done step by step, process focused, fine for simple tasks
- OOP (Python): objects carry their own attributes and functions, data focused, suits complex tasks
Everything in Python is an object of some class, see Classes and Objects in Python.
Indentation and Comments
In Python, indentation is a requirement, not a style choice. It defines which lines belong to a code block.
x = 5
if x > 0:
print("positive") # inside the if block
else:
print("not positive") # inside the else block
print("done") # outside both blocksComments are ignored by the interpreter:
- single line comment starts with
# - multi line comment is wrapped in triple quotes
"""..."""
Virtual Environments with Anaconda
Each project should get its own virtual environment, so two projects can use different versions of the same package (for example matplotlib 3.0.2 in one and 2.2.3 in another). Anaconda is a Python distribution for scientific computing that manages environments and packages.
conda create -n ee0005 python=3.6 # new environment with Python 3.6
conda activate ee0005 # enter it
conda install scipy # latest scipy
conda install matplotlib=2.2.3 # specific version
conda remove scipy # remove a package
conda deactivate # back to base
conda remove -n ee0005 --all # delete the environment (from outside it)
python hello.py # run a script