Python study notes

Published

March 17, 2023

Official python tutorial

This section contains my study notes on the official python tutorial.

Here is a link to the PEP 8 style guide.

Also it might be worthwile to look at the official language definition.

2. Using the Python Interpreter

the_world_is_flat = True
if the_world_is_flat:
  print("Be careful not to fall off!")
Be careful not to fall off!

3. An Informal Introduction to Python

Source

spam = 1 
text = "# This is not a comment because it's inside quotes."
squares = [1, 4, 9, 16, 25]
squares[0]
1
squares[-1]
25
squares[-3:]
[9, 16, 25]
squares[:]
[1, 4, 9, 16, 25]
squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
cubes = [1, 8, 27, 65, 125]  # something's wrong here
4 ** 3  # the cube of 4 is 64, not 65!
64
cubes[3] = 64  # replace the wrong value
cubes
[1, 8, 27, 64, 125]
cubes.append(216)  # add the cube of 6
cubes.append(7 ** 3)  # and the cube of 7
cubes
[1, 8, 27, 64, 125, 216, 343]
# Fibonacci series:
# the sum of two elements defines the next
a, b = 0, 1
while a < 10:
    print(a)
    a, b = b, a+b
0
1
1
2
3
5
8

6 Data structures

4 builtin data structures: * Lists - x = [1, 2, 3] * Tuples - x = 1, 2, 3 * Sets - x = {1, 2, 3} * Dictionaries x = {'a': 1, 'b': 2, 'c': 3}

Lists

fruits = ['apple', 'banana', 'orange']
fruits.reverse()
fruits
['orange', 'banana', 'apple']
fruits[1:]
['banana', 'apple']
fruits[:1]
['orange']
fruits.append('kiwi')
fruits
['orange', 'banana', 'apple', 'kiwi']

Tuples

  • “immutable lists”
a = 1, 2, 3, (2, 3, 4), 'a', ('Hello', 'This')
a[3]
(2, 3, 4)
1 < 3 > 1 < 27
True

Sets

x = {1, 2, 3}
x
{1, 2, 3}
y = {'a', 1, 3}
y
{1, 3, 'a'}
x & y
{1, 3}
x | y
{1, 2, 3, 'a'}
x.add(4)
x
{1, 2, 3, 4}
x.update([7, 0])
x
{0, 1, 2, 3, 4, 7}

Dictionaries

tel = {'jack': 4098, 'sape': 4139}
tel['jan-eggerik'] = 4898
tel['jan-eggerik'] = 'a'
'jack' in tel
True
'seb' in tel
False
del tel['sape']
list(tel)
['jack', 'jan-eggerik']
list(tel) <= ['jack', 'jan-eggerik']
True
dict([('a', 1), ('b', 2)])
{'a': 1, 'b': 2}
x = dict([(1, 'a'), (2, 'b')])
x[2]
'b'
x['a'] = 3
x
{1: 'a', 2: 'b', 'a': 3}
# sorted(x) - this will throw an error because of mixing of str and int
sorted(tel)
['jack', 'jan-eggerik']
x = 'string'
bool(x)
True
x = ''
bool(x)
False

Seaborn

import seaborn as sns
import matplotlib as mp
import matplotlib.pyplot as plt

# Apply the default theme
sns.set_theme()

# Load an example dataset


dots = sns.load_dataset("dots")

sns.set(rc={'figure.figsize':(10, 3)})

sns.relplot(
  data=dots, kind="line",
  x="time", y="firing_rate", col="align", # style = "choice",
  hue="choice", size="coherence", 
  facet_kws=dict(sharex=False)
  )

#mp.pyplot.show()
# sns.set_theme(style="whitegrid")

x = (5,5)

sns.set(rc={'figure.figsize': x})


# Load the example diamonds dataset
diamonds = sns.load_dataset("diamonds")

# Draw a scatter plot while assigning point colors and sizes to different
# variables in the dataset
f, ax = plt.subplots(figsize=x)
sns.despine(f, left=True, bottom=True)
clarity_ranking = ["I1", "SI2", "SI1", "VS2", "VS1", "VVS2", "VVS1", "IF"]
sns.scatterplot(x="carat", y="price",
                hue="clarity", size="depth",
                palette="ch:r=-.2,d=.3_r",
                hue_order=clarity_ranking,
                sizes=(1, 8), linewidth=0,
                data=diamonds, ax=ax)

Python libraries I want to look at

Python and quarto issues

  • Figure size seems to be not adjustable by chunk options if engine is jupyter
    • –> use knitr as engine
    • Here fig-size seems to work at least with matplotlib, other packages not tested
  • With knitr as engine, I think by default the following python executable is
system('which python', intern = TRUE)
[1] "/Users/seb/Library/r-miniconda-arm64/envs/sbloggel/bin/python"
import sys
print(sys.executable)
/Users/seb/Library/r-miniconda-arm64/envs/sbloggel/bin/python
  • In the default environment, I was able to install packages with the following command:
library('reticulate')
# conda_install('r-reticulate', 'matplotlib')
 

# This did not work:
# py_install("pandas")

Pandas