Chapter 14 Python Fundamentals
This unit covers Python fundamentals. All the codes here are Python codes.
14.1 Set up Environment
- Install Anaconda
- Install Jupyter Notebook/Lab (See Jupyter Notebook installation documentation)
- Run the codes in notebooks
14.2 Conda Environment
- We can create a conda environment using:
$ conda create --name XXX
Please specify the conda environment name XXX
on your own.
- Similarly, when you add the self-defined conda environment to the notebook kernel list:
$ python -m ipykernel install --user --name=XXX
You need to specify the conda environment name XXX
.
There are several important things here:
You need to install the relevant modules AFTER you activate the conda environment in the terminal.
You need to add the kernel name with
python -m ipykernel install --user --name=XXX
within the conda enviroment as well.In other words, you need to install the module ipykernel in the target conda environment as well.
After a few trial-and-errors, I think the best environment setting is that you only add the kernel name (conda environment) to ipykernel within the conda environment. Do not add the conda environment again in your base python environment.
What’s even better is to install jupyter in your conda environment (python-notes) and run your notebook from this python-notes as well.
14.4 Data Structure
- List
- Tuple
- Dictionary
vocab = ['cat', 'dog', 'bird']
word_pos = (('cat','n'),('dog','n'),('bark','v'))
word_freq = {'cat': 3, 'dog': 1, 'bird': 5}
print(vocab)
['cat', 'dog', 'bird']
<class 'list'>
<class 'tuple'>
<class 'dict'>
List and Tuple look similar but they differ in one important aspect: List is mutable while Tuple is Immutable.
That is, when a List is created, particular elements of it can be reassigned. Along with this, the entire list can be reassigned. Elements and slices of elements can be deleted from the list. But these changes will not be possible for a Tuple.14.5 String
['human', 'dog', 'bird']
'tuple' object does not support item assignment
<class 'str'>
'won'
In Python, a String
functions as a List
:
True
'wonderfulbook'
'w o n d e r f u l'
- Useful functions for
String
:
' this is a sentence example with leading/trailing spaces. '
' This Is A Sentence Example With Leading/Trailing Spaces. '
' THIS IS A SENTENCE EXAMPLE WITH LEADING/TRAILING SPACES. '
' this is a sentence example with leading/trailing spaces. '
' This is a sentence example with leading/trailing spaces.'
'This is a sentence example with leading/trailing spaces. '
'This is a sentence example with leading/trailing spaces.'
5
' Thwas was a sentence example with leading/trailing spaces. '
- String formatting
'DIARY has 50 words'
14.9 Python Scripts
Depending on the editor you use, you may have two types of Python script files:
*.py
: A simple python script file*.ipynb
: A Jupyter Notebook file which needs to be run in Jupyter Lab/Notebook