I am working on the file "Chapter5/ParameterEstimation.ipynb".
The first task is:
5.6 Simple Examples of Bayesian Analysis: Parameter Estimation
MLE vs Bayesian Estimation
MLE:

We sought a point value for a parameter that maximized the likelihood
No priors
Probability statements about parameters were meaningless

Bayesian Estimation:

We maximize the posterior to get a probability density function for the parameters(s) rather than a single point
We can update data with prior assumptions to make probability statements about the parameters

Parameter Estimation for a Gaussian Distribution
Known errors
Suppose we have a set of $N$ values ${x_{i}}$ drawn from a Gaussian distribution with known errors $\sigma_{i}$. If ${x_{i}}$ are i.i.d., the likelihood of the entire data set is just the product of the likelihood for each particular value:
$$ p({x_i}\,|\,\mu,\,I) = {\displaystyle \prod_{i=1}^{N}} \, \frac{1}{\sqrt{2\pi}\sigma_i} \mbox{exp}\Big(\frac{-(x_i-\mu)^2}{2\sigma_i^2}\Big) $$
If we take our prior to be uniform such that in the range $\mu_{min}<\mu<\mu_{max}$
$$p(\mu|I)=C,\hspace{1cm}$$
where $$C=(\mu_{max}-\mu_{min})^{-1}$$
then the posterior pdf for the parameter $\mu$ is
$$ p(\mu|{x_i}, {\sigma_i},I) = p({x_i}|\mu,I)\,p(\mu|I)$$
and its logarithm is
$$ L_p\equiv\mbox{ln}[p(\mu|{x_i}, {\sigma_i},I)] = \mbox{constant} - {\displaystyle \sum_{i=1}^{N}} \frac{(x_i-\mu)^2}{2\sigma_i^2}$$
Maximizing the parameter $\mu$ via $dL_p/d\mu|_{\mu=\mu_0}=0$ gives
$$ \mu_0=\frac{\Sigma_{i=1}^{N}w_ix_i}{\Sigma_{i=1}^{N}w_i} $$
and the width of the posterior pdf for $\mu$ is
$$ \sigma_\mu=\Big(-\frac{d^2L_p}{d\mu^2}|_{\mu=\mu_0}\Big)^{-1/2}=\Big({\displaystyle \sum_i}w_i\Big)^{-1/2}$$
We see that using a flat prior gave us the same result as the maximum likelihood estimation. If we had assumed our errors were homoscedastic, this would just reduce to the standard result given by
$$ \mu_0=\frac{1}{N}{\displaystyle \sum_{i=1}^N}x_i$$
Conclusion: when errors are known, the posterior pdf for $\mu$ is Gaussian. What happens when $\sigma$ is unknown?
Unknown errors (two-dimentional posterior)
Now the...
Can you write Python code for it?

# Author: Jake VanderPlas
# License: BSD
#   The figure produced by this code is published in the textbook
#   "Statistics, Data Mining, and Machine Learning in Astronomy" (2013)
#   For more information, see http://astroML.github.com
#   To report a bug or issue, use the following forum:
#    https://groups.google.com/forum/#!forum/astroml-general

def gauss_logL(xbar, V, n, sigma, mu):
    """Equation 5.58: gaussian likelihood"""
    return (-(n + 1) * np.log(sigma)
            - 0.5 * n * ((xbar - mu) ** 2 + V) / sigma ** 2)

#------------------------------------------------------------
# Define the grid and compute logL
sigma = np.linspace(1, 5, 70)
mu = np.linspace(-3, 5, 70)
xbar = 1
V = 4
n = 10

logL = gauss_logL(xbar, V, n, sigma[:, np.newaxis], mu)
logL -= logL.max()

#------------------------------------------------------------
# Plot the results
fig = plt.figure(figsize=(9, 7.75))
plt.imshow(logL, origin='lower',
           extent=(mu[0], mu[-1], sigma[0], sigma[-1]),
           cmap=plt.cm.binary,
           aspect='auto')

plt.colorbar().set_label(r'$\log(L)$')
plt.clim(-5, 0)

plt.contour(mu, sigma, convert_to_stdev(logL),
            levels=(0.683, 0.955, 0.997),
            colors='k')

plt.text(0.5, 0.93, r'$L(\mu,\sigma)\ \mathrm{for}\ \bar{x}=%d,\ V=%d,\ n=%d$'%(xbar,V,n),
         bbox=dict(ec='k', fc='w', alpha=0.9),
         ha='center', va='center', transform=plt.gca().transAxes)

plt.xlabel(r'$\mu$')
plt.ylabel(r'$\sigma$');


I am working on the file "Chapter5/ParameterEstimation.ipynb".
The first task is:
If we knew the width of our distribution $\sigma$, then the posterior probability $p(\mu|\sigma)$ would be Gaussian. However we don't know $\sigma$, so we have to marginalize our posterior by integrating over all possible values of $\sigma$
$$ p(\mu|{x_i}, I)=\int_0^\infty p(\mu, \sigma|{x_i}, I)\,d\sigma$$
which gives a marginal pdf for $p(\mu)$ which is proportional to
$$ p(\mu|{x_i}, I) \propto \Big[1+\frac{(\bar{x}-\mu)^2}{V}\Big]^{-N/2} $$
Thus in cases when N is small and the errors are unkown and homoscedastic, the underlying distribution for the posterior follows a Student'ts $t$ distribution.
In the limit of large N, this essentially approaches a Gaussian. Moreover, marginalizing with repsect to $\mu$ gives a posterior pdf for $\sigma$ that resembles a $\chi^2$ distribution
$$ p(\sigma|{x_i}, I) \propto \frac{1}{\sigma^N}\mbox{exp}\Big(\frac{-NV}{w\sigma^2}\Big) $$
Can you write Python code for it?

# Author: Jake VanderPlas
# License: BSD
#   The figure produced by this code is published in the textbook
#   "Statistics, Data Mining, and Machine Learning in Astronomy" (2013)
#   For more information, see http://astroML.github.com
#   To report a bug or issue, use the following forum:
#    https://groups.google.com/forum/#!forum/astroml-general

#------------------------------------------------------------
# Define functions for computations below
#  These are expected analytic fits to the posterior distributions
def compute_pmu(mu, xbar, V, n):
    return (1 + (xbar - mu) ** 2 / V) ** (-0.5 * n)

def compute_pmu_alt(mu, xbar, V, n):
    return (1 + (xbar - mu) ** 2 / V) ** (-0.5 * (n - 1))

def compute_psig(sig, V, n):
    return (sig ** -n) * np.exp(-0.5 * n * V / sig ** 2)

def compute_psig_alt(sig, V, n):
    return (sig ** -(n - 1)) * np.exp(-0.5 * n * V / sig ** 2)

def gaussian(x, mu, sigma):
    return np.exp(-0.5 * (x - mu) ** 2 / sigma ** 2)

#------------------------------------------------------------
# Draw a random sample from the distribution, and compute
# some quantities
n=10
#n = 77
xbar = 1
V = 4
sigma_x = np.sqrt(V)

np.random.seed(10)
xi = np.random.normal(xbar, sigma_x, size=n)

mu_mean, sig_mean = mean_sigma(xi, ddof=1)

# compute the analytically expected spread in measurements
mu_std = sig_mean / np.sqrt(n)
sig_std = sig_mean / np.sqrt(2 * (n - 1))

#------------------------------------------------------------
# bootstrap estimates
mu_bootstrap, sig_bootstrap = bootstrap(xi, 1E6, mean_sigma,
                                        kwargs=dict(ddof=1, axis=1))

#------------------------------------------------------------
# Compute analytic posteriors

# distributions for the mean
mu = np.linspace(-3, 5, 1000)
dmu = mu[1] - mu[0]

pmu = compute_pmu(mu, xbar, V, n)
pmu /= (dmu * pmu.sum())

pmu2 = compute_pmu_alt(mu, xbar, V, n)
pmu2 /= (dmu * pmu2.sum())

pmu_norm = gaussian(mu, mu_mean, mu_std)
pmu_norm /= (dmu * pmu_norm.sum())

mu_hist, mu_bins =...


I am working on the file "Chapter5/ParameterEstimation.ipynb".
The first task is:
Taking the derivative of $L_p$ with respect to $\mu$ and setting it to zero gives a maximum value for $\mu=\mu_0$
$$ \mu_0=\frac{\Sigma_i w_i x_i}{\Sigma_i w_i} $$
but with different weights
$$ w_i = \frac{1}{\sigma_0^2 + e_i^2} $$
We can provide an additional constraint for $\sigma_0$ by setting the derivative of $L_p$ with respect to $\sigma$ equal to zero, but this does not lead to a closed form expression and requires simulatenously solving two complicated equations. Instead, the sample median is actually a pretty good estimator of $\mu_0$, and the maximum width can be estimated as
$$ \sigma_0^2=\zeta^2\sigma_G^2-e_{50}^2 $$
where $\sigma_G$ is the quartile-based estimator, $e_{50}$ is the median error, and $\zeta=\mbox{median}(\tilde{\sigma_i})/\mbox{mean}(\tilde{\sigma_i})$, where
$$ \tilde{\sigma_i} = (\sigma_G^2+e_i^2-e_{50}^2)^{1/2} $$
Can you write Python code for it?

# Author: Jake VanderPlas
# License: BSD
#   The figure produced by this code is published in the textbook
#   "Statistics, Data Mining, and Machine Learning in Astronomy" (2013)
#   For more information, see http://astroML.github.com
#   To report a bug or issue, use the following forum:
#    https://groups.google.com/forum/#!forum/astroml-general

def gaussgauss_logL(xi, ei, mu, sigma):
    """Equation 5.63: gaussian likelihood with gaussian errors"""
    ndim = len(np.broadcast(sigma, mu).shape)

    xi = xi.reshape(xi.shape + tuple(ndim * [1]))
    ei = ei.reshape(ei.shape + tuple(ndim * [1]))

    s2_e2 = sigma ** 2 + ei ** 2
    return -0.5 * np.sum(np.log(s2_e2) + (xi - mu) ** 2 / s2_e2, 0)

#------------------------------------------------------------
# Define the grid and compute logL
np.random.seed(5)
mu_true = 1.
sigma_true = 1.
N = 10
ei = 3 * np.random.random(N)
xi = np.random.normal(mu_true, np.sqrt(sigma_true ** 2 + ei ** 2))

sigma = np.linspace(0.01, 5, 70)
mu = np.linspace(-3, 5, 70)

logL = gaussgauss_logL(xi, ei, mu, sigma[:, np.newaxis])
logL -= logL.max()

#------------------------------------------------------------
# plot the results
fig = plt.figure(figsize=(9, 7.75))
plt.imshow(logL, origin='lower',
           extent=(mu[0], mu[-1], sigma[0], sigma[-1]),
           cmap=plt.cm.binary,
           aspect='auto')
plt.colorbar().set_label(r'$\log(L)$')
plt.clim(-5, 0)

plt.text(0.5, 0.93,
         (r'$L(\mu,\sigma)\ \mathrm{for}\ \bar{x}=1,\ '
          r'\sigma_{\rm true}=1,\ n=10$'),
         bbox=dict(ec='k', fc='w', alpha=0.9),
         ha='center', va='center', transform=plt.gca().transAxes)

plt.contour(mu, sigma, convert_to_stdev(logL),
            levels=(0.683, 0.955, 0.997),
            colors='k')

plt.xlabel(r'$\mu$')
plt.ylabel(r'$\sigma$');


I am working on the file "Chapter6/6-Linked_Structures.ipynb".
The first task is:
Since we did not define a method to show the value stored, we cannot see the value. However the values we passed to each variable is stored.

Now to make it a linked list, we have to establish a connection. To achieve this we can add another data field called next into our constructor.
Can you write Python code for it?

class ListNode:
    def __init__(self, data):
        self.data = data
        self.next = None

# Initial creation of nodes
a = ListNode(11)
b = ListNode(52)
c = ListNode(18)


I am working on the file "Chapter6/6-Linked_Structures.ipynb".
The first task is:
This is will give us just the containers that we can store data into.
Can you write Python code for it?

a = ListNode(11)
b = ListNode(52)
c = ListNode(18)

print(a)


I am working on the file "Chapter7_BayesianMachineLearning/DontOverfit.ipynb".
The first task is:
Develop Tim's model
He mentions that the X variables are from a Uniform distribution. Let's investigate this:
Can you write Python code for it?

figsize(12, 4)

hist(training_data.flatten())
print training_data.shape[0] * training_data.shape[1]


I am working on the file "Chapter7_BayesianMachineLearning/DontOverfit.ipynb".
The first task is:
looks pretty right
Can you write Python code for it?

import pymc as pm

to_include = pm.Bernoulli("to_include", 0.5, size=200)

coef = pm.Uniform("coefs", 0, 1, size=200)

@pm.deterministic
def Z(coef=coef, to_include=to_include, data=training_data):
    ym = np.dot(to_include * training_data, coef)
    return ym - ym.mean()

@pm.deterministic
def T(z=Z):
    return 0.45 * (np.sign(z) + 1.1)

obs = pm.Bernoulli("obs", T, value=training_labels, observed=True)

model = pm.Model([to_include, coef, Z, T, obs])
map_ = pm.MAP(model)
map_.fit()

mcmc = pm.MCMC(model)

mcmc.sample(100000, 90000, 1)

(np.round(T.value) == training_labels).mean()

t_trace = mcmc.trace("T")[:]
(np.round(t_trace[-500:-400, :]).mean(axis=0) == training_labels).mean()

t_mean = np.round(t_trace).mean(axis=1)

imshow(t_trace[-10000:, :], aspect="auto")
colorbar()

figsize(23, 8)
coef_trace = mcmc.trace("coefs")[:]
imshow(coef_trace[-10000:, :], aspect="auto", cmap=pyplot.cm.RdBu, interpolation="none")

include_trace = mcmc.trace("to_include")[:]

figsize(23, 8)
imshow(include_trace[-10000:, :], aspect="auto", interpolation="none")


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Above: Fit looks pretty wild, too.  Here's a clear example of how overfitting is associated with very large magnitude estimated coefficients.

#
#
Ridge Regression
Ridge regression aims to avoid overfitting by adding a cost to the RSS term of standard least squares that depends on the 2-norm of the coefficients $\|w\|$.  The result is penalizing fits with large coefficients.  The strength of this penalty, and thus the fit vs. model complexity balance, is controled by a parameter lambda (here called "L2_penalty").
Define our function to solve the ridge objective for a polynomial regression model of any degree:
Can you write Python code for it?

def polynomial_ridge_regression(data, deg, l2_penalty):
    model = graphlab.linear_regression.create(polynomial_features(data,deg),
                                              target='Y', l2_penalty=l2_penalty,
                                              validation_set=None,verbose=False)
    return model


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Add random Gaussian noise to y
Can you write Python code for it?

random.seed(1)
e = graphlab.SArray([random.gauss(0,1.0/3.0) for i in range(n)])
y = y + e


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Create a function to plot the data, since we'll do it many times
Can you write Python code for it?

def plot_data(data):
    plt.plot(data['X1'],data['Y'],'k.')
    plt.xlabel('x')
    plt.ylabel('y')

plot_data(data)


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Define some useful polynomial regression functions
Define a function to create our features for a polynomial regression model of any degree:
Can you write Python code for it?

def polynomial_features(data, deg):
    data_copy=data.copy()
    for i in range(1,deg):
        data_copy['X'+str(i+1)]=data_copy['X'+str(i)]*data_copy['X1']
    return data_copy


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Explore the lasso solution as a function of a few different penalty strengths
We refer to lambda in the lasso case below as "l1_penalty"
Can you write Python code for it?

for l1_penalty in [0.0001, 0.01, 0.1, 10]:
    model = polynomial_lasso_regression(data, deg=16, l1_penalty=l1_penalty)
    print 'l1_penalty = %e' % l1_penalty
    print 'number of nonzeros = %d' % (model.coefficients['value']).nnz()
    print_coefficients(model)
    print '\n'
    plt.figure()
    plot_poly_predictions(data,model)
    plt.title('LASSO, lambda = %.2e, # nonzeros = %d' % (l1_penalty, (model.coefficients['value']).nnz()))


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Find the value of lambda, $\lambda_{\mathrm{CV}}$, that minimizes the LOO cross validation error, and plot resulting fit
Can you write Python code for it?

best_l2_penalty

model = polynomial_ridge_regression(data, deg=16, l2_penalty=best_l2_penalty)
print_coefficients(model)

plot_poly_predictions(data,model)


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Fit a degree-2 polynomial
Fit our degree-2 polynomial to the data generated above:
Can you write Python code for it?

model = polynomial_regression(data, deg=2)


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Fit a degree-4 polynomial
Can you write Python code for it?

model = polynomial_regression(data, deg=4)
print_coefficients(model)
plot_poly_predictions(data,model)


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Inspect learned parameters
Can you write Python code for it?


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Let's look at fits for a sequence of increasing lambda values
Can you write Python code for it?

for l2_penalty in [1e-25, 1e-10, 1e-6, 1e-3, 1e0,1e2]:
    model = polynomial_ridge_regression(data, deg=16, l2_penalty=l2_penalty)
    print 'lambda = %.2e' % l2_penalty
    print_coefficients(model)
    print '\n'
    plt.figure()
    plot_poly_predictions(data,model)
    plt.title('Ridge, lambda = %.2e' % l2_penalty)


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Perform a ridge fit of a degree-16 polynomial using a very small penalty strength
Can you write Python code for it?

model = polynomial_ridge_regression(data, deg=16, l2_penalty=1e-25)
print_coefficients(model)

plot_poly_predictions(data,model)


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Run LOO cross validation for "num" values of lambda, on a log scale
Can you write Python code for it?

l2_penalty_values = numpy.logspace(-4, 10, num=10)
l2_penalty_mse,best_l2_penalty = loo(data, 16, l2_penalty_values)


I am working on the file "Chapter8/Overfitting_Demo_Ridge_Lasso.ipynb".
The first task is:
Woah!!!!  Those coefficients are crazy!  On the order of 10^6.
Can you write Python code for it?


I am working on the file "Chapter_03_Model_Managers_and_QuerySets.ipynb".
The first task is:
Connecting Data through Relations
Can you write Python code for it?

djt = Post.objects.create(
    title='Django Training',
    slug='django-training',
    text=(
        "Learn Django in a classroom setting "
        "with JamBon Software."),
)
djt

djt.pub_date = date(2013, 1, 18)
djt.save()
djt

type(djt.tags)

type(djt.startups)

djt.tags.all()

djt.startups.all()

django = Tag.objects.get(slug__contains='django')
djt.tags.add(django)
djt.tags.all()

django.blog_posts.all()  # a "reverse" relation

django.startup_set.add(jb)  # a "reverse" relation
django.startup_set.all()

jb.tags.all()  # the "forward" relation

# on more time, for repetition!
djt

# "forward" relation
djt.startups.add(jb)
djt.startups.all()

jb.blog_posts.all()  # "reverse" relation


I am working on the file "Chapter_03_Model_Managers_and_QuerySets.ipynb".
The first task is:
Creation and Destruction with Managers
Can you write Python code for it?

type(Tag.objects)  # a model manager

Tag.objects.create(name='Video Games', slug='video-games')

# create multiple objects in a go!
Tag.objects.bulk_create([
    Tag(name='Django', slug='django'),
    Tag(name='Mobile', slug='mobile'),
    Tag(name='Web', slug='web'),
])

Tag.objects.all()

Tag.objects.all()[0]  # acts like a list

type(Tag.objects.all())  # is not a list

# managers are not accessible to model instances, only to model classes!
try:
    edut.objects
except AttributeError as e:
    print(e)


I am working on the file "Chapter_03_Model_Managers_and_QuerySets.ipynb".
The first task is:
Data in Memory vs Data in the Database
Can you write Python code for it?

jb = Startup.objects.create(
    name='JamBon Software',
    slug='jambon-software',
    contact='django@jambonsw.com',
    description='Web and Mobile Consulting.\n'
                'Django Tutoring.\n',
    founded_date=date(2013, 1, 18),
    website='https://jambonsw.com/',
)
jb  # this output only clear because of __str__()

jb.founded_date

jb.founded_date = date(2014,1,1)
# we're not calling save() !
jb.founded_date

# get version in database
jb = Startup.objects.get(slug='jambon-software')
# work above is all for nought because we didn't save()
jb.founded_date


I am working on the file "Chapter_03_Model_Managers_and_QuerySets.ipynb".
The first task is:
Interacting With the Database
Can you write Python code for it?

edut = Tag(name='Education', slug='education')

edut

edut.save()

edut.delete()

edut  # still in memory!


I am working on the file "Chapter_03_Model_Managers_and_QuerySets.ipynb".
The first task is:
Methods of Data Retrieval
Can you write Python code for it?


I am working on the file "Chapter_03_Model_Managers_and_QuerySets.ipynb".
The first task is:
The get method
Can you write Python code for it?

Tag.objects.get(slug='django')

type(Tag.objects.all())

type(Tag.objects.get(slug='django'))

# case-sensitive!
try:
    Tag.objects.get(slug='Django')
except Tag.DoesNotExist as e:
    print(e)

# the i is for case-Insensitive
Tag.objects.get(slug__iexact='DJANGO')

Tag.objects.get(slug__istartswith='DJ')

Tag.objects.get(slug__contains='an')

# get always returns a single object
try:
    # djangO, mObile, videO-games
    Tag.objects.get(slug__contains='o')
except Tag.MultipleObjectsReturned as e:
    print(e)


I am working on the file "Chapter_03_Model_Managers_and_QuerySets.ipynb".
The first task is:
values and values_list
Can you write Python code for it?

Tag.objects.values_list()

type(Tag.objects.values_list())

Tag.objects.values_list('name', 'slug')

Tag.objects.values_list('name')

Tag.objects.values_list('name', flat=True)

type(Tag.objects.values_list('name', flat=True))


I am working on the file "Chapters-colab/Chapter_01_Getting_Started_with_Variables_and_Values.ipynb".
The first task is:
1.2 Calculations
Apart from printing some text to your screen, you can also use Python to do calculations. The code is actually really simple - you probly know most of it from your calculator!
Can you write Python code for it?

# summing
print(3+2)

# subtracting
print(7-1)

# multiplication
print(3*3)

# division
print(10/3)

# power
print(5**2)

# combining stuff
print(5*2-3+4/2)

#using brakets to tell python what to calculate first:
print((5+5)*(8+2))
# compared to:
print(5+5*8+2)
#Can you tell what is happening in these examples?


I am working on the file "Chapters-colab/Chapter_01_Getting_Started_with_Variables_and_Values.ipynb".
The first task is:
2. Variables and values
Instead of providing the string directly as an argument to the print function, we can also create a variable that refers to the string value "Hello, world!".
When you pass this variable to the print() function, you get the same result as before:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_01_Getting_Started_with_Variables_and_Values.ipynb".
The first task is:
2.1 Variable assignment
If you vaguely remember your math classes in school, this should look familiar. It is basically the same notation with the name of the variable on the left, the value on the right, and the '=' sign in the middle. This is what is called assignment. We stored a value and named it using the '=' symbol, so that we can easily use it later on without having to type the particular value.
We can use the box metaphor to further explain this concept. The variable x above behaves pretty much like a box on which we write an x with a thick, black marker to find it back later. In this box we can put whatever we want, such as a piece of text or a numerical value. In Python, the term variable refers to such a box, whereas the term value refers to what is inside this box.

Note that we can re-use variable names for other values, but that any assignment will overwrite the original value! In other words: when you re-asign a variable, you remove the content of the box and put something new in it. Each variable will always contain the value that you last assigned to it.
Can you write Python code for it?

text = "I like apples"
print(text)
text = "I like oranges"
print(text)


I am working on the file "Chapters-colab/Chapter_01_Getting_Started_with_Variables_and_Values.ipynb".
The first task is:
Chapter 1 - Getting Started with Variables and Values
This notebook uses code snippets and explanations from this course.
Welcome to the course! In this course we will learn how to load, process and save data using a versatile programming language: Python. We are going to practise Python using Notebooks. These Notebooks contain instructions and so called 'code blocks'. The instructions are paragraphs of text that explain the concepts we are going to use. The 'code blocks' contain Python code.
Note: Jupyter has integrated different languages now! This means that your menue is probably shown in your language rather than in English. Please take this into account when reading the instructions.
Notebooks are pretty straightforward. Some tips:

Cells in a notebook contain code or text. If you run a cell, it will either run the code or render the text.
There are five ways to run a cell:
Click the 'play' button next to the 'stop' and 'refresh' button in the toolbar.
Alt + Enter runs the current cell and creates a new cell.
Ctrl + Enter runs the current cell without creating a new cell. (Cmd + Enter on a Mac.)
Shift + Enter runs the current cell and moves to the next one.
Use the menu and select Run/Run selected cells or Run/Run all cells to run the entire notebook (not recommended at this stage).

You can create a new cell by hitting the '+' button on top.
The instructions are written in Markdown. You can select whether a cell should contain markdown or code by clicking on the drop-down menue on top. Here is a nice Markdown cheatsheet if you want to write some more.
Explore the menus for more options! You can even create a presentation using Notebooks.

Hint: when you're writing Python code, press Tab to auto-complete your variable names! We will introduce you to variable names in this notebook.
At the end of this chapter, you will be able to:

print information to your screen using the built-in function print()
assign values to variables (using valid and clear variable names)
do calculations in Python
have an...
Can you write Python code for it?

# this will print some text
print("Hello, world!")


I am working on the file "Chapters-colab/Chapter_01_Getting_Started_with_Variables_and_Values.ipynb".
The first task is:
Exercise 2:
Rewrite the code you wrote for exercise 1 by assigning each of the numerical values to a variable with a clear name. Then use these variables to calculate the number of seconds in seven years. We've made a start for you below:
Can you write Python code for it?

days_in_year = 365
# assign each of the values to meaningful variable names

seconds_in_seven_years = days_in_year * # finish this line
print(seconds_in_seven_years)


I am working on the file "Chapters-colab/Chapter_01_Getting_Started_with_Variables_and_Values.ipynb".
The first task is:
Exercise 3:
Run the following code block and see what happens. Can you fix the invalid variable names? You should get no error in the end.
Can you write Python code for it?

eggs = 3
_eggs = 6
5eggs = 5
eggs$ = 1
eggs123 = 9
ten_eggs = 10
TwelveEggs = 8
twelve.eggs = 12


I am working on the file "Chapters-colab/Chapter_01_Getting_Started_with_Variables_and_Values.ipynb".
The first task is:
Exercise 4:
Can you write some code that swaps the values of these two variables? Hint: the easiest way is to create an extra variable. If you like a more challenging exercise, try to swap the values without using an extra variable.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_01_Getting_Started_with_Variables_and_Values.ipynb".
The first task is:
Exercises
Exercise 1:
Use Python as a calculator to calculate the number of seconds in seven years (in one line of code). Assign the output to a variable with a clear variable name. Print the result.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_01_Getting_Started_with_Variables_and_Values.ipynb".
The first task is:
Have a look at this code at Python Tutor to see what's happening!
2.4 User input
Up until now we have defined the values stored in the variables ourselves. However, we can also ask for input from a user. We'll make use of another built-in function: input(). This takes user input and returns it as a string. Try it below:
Can you write Python code for it?

text = input("Please enter some text: ")
print(text)


I am working on the file "Chapters-colab/Chapter_01_Getting_Started_with_Variables_and_Values.ipynb".
The first task is:
However, variable names are only valid if they:

start with a letter or underscore (_)
only contain letters, numbers and underscores

Even though you could use any variable name as long as they are valid, there are some naming conventions that are explained in the PEP8 Style Guide for Python Code. For now, it's enough to remember the following for naming your variables:

use clear, meaningful, descriptive variable names so that your code will remain understandable
use the lowercase_with_underscores style, with lowercase characters and underscores for separating words
do not use built-in names, such as print or sum (these will turn green in Jupyter Notebooks)

For example, the following variable name is valid, much more descriptive than x would be and follows the naming conventions:
Can you write Python code for it?

seconds_in_seven_years = 220752000
print(seconds_in_seven_years)


I am working on the file "Chapters-colab/Chapter_01_Getting_Started_with_Variables_and_Values.ipynb".
The first task is:
What happened here? Well, Python has a large set of built-in functions, and print() is one of them. When you use this function, print() outputs its argument to the screen. 'Argument' is a fancy word for "object you put in a function". In this case, the argument is the string "Hello, world!". And 'string' just means "a sequence of characters".
Did you also notice the first line starting with a hash (#) character? This is called a comment. We use comments to document our code and explain what's happening. These lines are not executed in Python. We will use them a lot in this course to make our code easy to understand!
Can you edit the block below in such a way that it will print out your own name?
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_01_Getting_Started_with_Variables_and_Values.ipynb".
The first task is:
When we have stored values inside variables, we can do interesting things with these variables. Run the following code block to see what happens.
Can you write Python code for it?

x = 3
print(x)
print(x * x)
print(x + x)
print(x - 6)


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
1.1 What can you do with an object: type affordances
What you need to know at this point is that each type has particular affordances, or associated things that you can do with them. When something is of a numeric type (integer, float), the Python interpreter knows that you can perform mathematical operations with that object. You cannot use those operations with strings, because it doesn't make sense to take the square root of the string "Hello, world!".
It's the same with vehicles and food in real life. Anything that is of the type vehicle can be used to get around and possibly transport goods. But you cannot eat a vehicle. Anything that is of the type food is edible, but it's pretty difficult to use food for transportation (try biking home on a carrot).
So depending on the type, Python interprets objects in a different way and you can do different thing with them. For example, Python will throw a TypeError if you try to divide one string by another:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
1.2 Casting types (e.g. turning integers into strings)
Sometimes it would make sense to convert one type into the other. This is called casting. For example, we can imagine a case like this:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
As we can see, “+” means “addition” if we use it with integers and “concatenate” (put together) if we use it with strings (or lists). If we try to combine both types, Python will indicate that the operation you are trying to do does not make sense:
Can you write Python code for it?

var3 = 4 + "hello"
print(var3)

var4 = list_1 +5
print(var4)


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
Chapter 2 - Basic Data Types (Integers and Floats)
This notebook uses code snippets and explanations from this course.
In the previous chapter, you have made a first start with programming in Python. We have already seen some basic data types: strings and numerical values. In this chapter, we will further explain the concept of data types and have a closer look at the numerical ones: integers and floats.
At the end of this chapter, you will be able to:

understand the concept of data types
check and convert the type of an object
understand and work with two numeric types: integers and floats

If you want to learn more about these topics, you might find the following links useful:

Documentation: Python Built-in Types
Video: Variables and Types in Python
Video: Integers, floats and maths
Video: Working with Numeric Data

If you have questions about this chapter, please contact us (cltl.python.course@gmail.com).
1. Basic Data Types
Python is an object-oriented programming language. This means that it treats every piece of data like some kind of object that can be manipulated and passed around. Python has the following basic types of objects:

String: for representing text.
Integer: for representing whole numbers.
Float: for representing numbers with decimals.
Tuple: for representing combinations of objects.
List: for representing ordered sequences of objects.
Set: for representing unordered sets of objects.
Dictionary: to represent mappings between objects.
Booleans: too represent the truth values True or False.
..and functions: to manipulate objects, or to produce new objects given some input.

You can also read about the types in Python in the documentation here, and we will work with each of them during the course. In this block, we will focus on strings, integers floats and booleans. We will also show you some other types, which will be explained in more detail in the next block.
Here's an example of each type:
Can you write Python code for it?

a_string       = 'test'
an_integer     = 4
a_float        = 3.14
a_tuple        = (2,5)
a_list         = [1,2,3,1,2,3,'a','b','c']
a_set          = {1,2,3,4,'apple'}
a_dict         = {'milk':2, 'cheese':1, 'pickles':45}
a_function     = print
a_bool         = True
another_bool   = False


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
Exercise 2:
What could be left out in the following piece of code without changing the result (the value of x)?
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
Exercise 4:
Use input() to ask a user for any number. Divide this number by nr1 and store the result as a variable. Print the value and the type of this variable.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
Exercise 5:
The following cells will throw errors or not do what you expect. Can you figure out what is going on and fix it?
Can you write Python code for it?

x = 10
y = "5"
z = x / y
print(z)

count = 1
count = count += 1
count

# This does something, but it is probably not what you want. Can you fix it?
# As an extra exercise: can you figure out what =+ does do?

count = 1
count =+ 1
print(count)


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
Exercises
Exercise 1:
Does the following give you the result that you expected? What is the type of result? What do you need to change if you simply want to do a calculation?
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
Inspecting python objects: The type function
We can use the type() function to check object types. Let's use it for a selection of our newly defined objects:
Can you write Python code for it?

type(a_string)

type(a_function)

type(an_integer)


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
Note on reading and interpreting errors
Even though it may seem a bit annoying when your code throws an error, try to see it as a helpful message informing you about why something does not work. Consider the error message above. It has the following components:

A name: TypeError
A pointer to the line in which your code goes wrong: ---> 1
A message: unsupported operand type(s) for /: 'str' and 'str'

What does this tell us?

Something is wrong with the type of the object and what we're trying to do.
Where does it go wrong? Easy here - in line 1 (our code only has a single line, but imaging how helpful this information is if you're dealing with 50 lines of code...)
What is wrong? In line 1, we're trying to do something with strings. The message tells us that '/' (i.e. the division operator) is an 'unsupported operand' for objects of the type string. In plain English: Python does not know what to do when we're combining strings with the division operator. The reason for this is that strings cannot be used in divisions.

This gives us enough information to figure out what is wrong. Here, there is not really anything we can fix - we simply learned that it is not possible to divide strings. In other cases, the error message can also contain information about how to fix something in the code.
The same symbol can do different things depending on the type of object it is combined with
Sometimes, the same symbols can act like different operators depending on the type which they are used with. Compare the following two code blocks:
Can you write Python code for it?

var1 = 1 + 4
print(var1)

var2 = "hello " + "there'"
print(var2)

list_1 = [1, 2, 3]
list_2 = [4, 5, 6]

list_3 = list_1 + list_2
print(list_3)


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
The difference between integers and floats is of course important for divisions where you often (automatically) end up with floats This is known as implicit type conversion, or 'coercion'. In some cases, this can lead to problems, for instance if the rest of your code expects integers, but suddenly has to deal with floats (but you do not have to worry about it for now).
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
The same operation works just fine for integers:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
This special shortcut (+=) is called an operator too. Apart from multiplication (+=), the operator has variants for subtraction (-=), multiplication (*=) and division (/=) too:
Can you write Python code for it?

number_of_books -= 5
print(number_of_books)
number_of_books *= 2
print(number_of_books)
number_of_books /= 2
print(number_of_books)


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
Using the operators we have learned about above, we can change the variables in our code as many times as we want. We can assign new values to old variables, just like we can put new or more things in the boxes which we already had. Say, for instance, that yesterday we counted how many books we have in our office and that we stored this count in our code as follows:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_02_Basic_Data_Types_(Integers_and_Floats).ipynb".
The first task is:
We get again a TypeError indicating that we cannot combine a string and an integer. Luckily, we can convert the string into an integer by applying int() to the variable x.
Can you write Python code for it?

x = "5"
y = 2
z = int(x) + y
print(z)
print(type(z))


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
2. Strings as sequences
2.1 String indices
Strings are simply sequences of characters. Each character in a string therefore has a position, which can be referred to by the index number of the position. The index numbers start at 0 and then increase to the length of the string. You can also start counting backwards using negative indices. The following table shows all characters of the sentence "Sandwiches are yummy" in the first row. The second row and the third row show respectively the positive and negative indices for each character:
| Characters     | S | a | n | d | w | i | c | h | e | s |    | a  |  r | e  |    |  y |  u |  m |  m |  y |
|----------------|---|---|---|---|---|---|---|---|---|---|----|----|----|----|----|----|----|----|----|----|
| Positive index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| Negative index |-20|-19|-18|-17|-16|-15|-14|-13|-12|-11|-10|-9|-8|-7|-6|-5|-4|-3|-2|-1|
You can access the characters of a string as follows:
Can you write Python code for it?

my_string = "Sandwiches are yummy"
print(my_string[1])
print(my_string[-1])


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
2.2 Slicing and indices applied to strings
Besides using single indices we can also extract a range from a string:
Can you write Python code for it?

my_string = "Sandwiches are yummy"
print(my_string[1:4])


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
3. Immutability
The mutability of an object refers to whether an object can change or not. Strings are immutable, meaning that they cannot be changed. It is possible to create a new string-object based on the old one, but we cannot modify the existing string-object. The cells below demonstrate this.
Can you write Python code for it?

# This is fine, because we are creating a new string. The old one remains unchanged:
fruit = 'guanabana'
island = fruit[:5]
print(island, 'island')
print(fruit, 'fruit')

# This works because we are creating a new string and overwriting our old one
fruit = fruit[5:] + 'na'
print(fruit)

# This attempt to change the ending into `aan' does not work because now we are trying to change an existing string
fruit[4:5] = 'an'
print(fruit)

# We could do this with a list though (don't worry about this yet - it is just meant to show the contrast)

fruits = ['cherry', 'blueberry', 'banana']
fruits[2:3] = ['rasperry', 'kiwi']
fruits

# If we want to modify a string by exchanging characters, we need to do:
fruit = fruit[:4] + 'an'
print(fruit)


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
5.1 Using f-strings
We can imagine that string concatenation can get rather confusing and unreadable if we have more variables. Consider the following example:
Can you write Python code for it?

name = "Pia"
age = 26
country = "Austria"
residence = "The Netherlands"

introduction = "Hello. My name is " + name + ". I'm " +  str(age) + " years old and I'm from " + country + \
", but I live in "+ residence +'.'
print(introduction)


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
6.1 Learning about methods
So how do you find out what kind of methods an object has? There are two options:

Read the documentation. See here for the string methods.
Use the dir() function, which returns a list of method names (as well as attributes of the object). If you want to know what a specific method does, use the help() function.

Run the code below to see what the output of dir() looks like.
The method names that start and end with double underscores ('dunder methods') are Python-internal. They are what makes general methods like len() work (len() internally calls the string.__len__() function), and cause Python to know what to do when you, for example, use a for-loop with a string.
The other method names indicate common and useful methods.
Can you write Python code for it?

# Run this cell to see all methods for strings
dir(str)


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
As you can see, Python now interprets this example as a single line of text. If we use the recommended way in Python to write multiline strings, with triple double or single quotes, you will see that the \n or newline symbol is automatically included.
Can you write Python code for it?

long_string = """A very long string
can also be split into multiple
sentences by enclosing the string
with three double or single quotes."""

print(long_string)

print()

another_long_string = '''A very long string
can also be split into multiple
sentences by enclosing the string
with three double or single quotes.'''

print(another_long_string)


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
Below we illustrate some of the string methods. Try to understand what is happening. Use the help() function to find more information about each of these methods.
Can you write Python code for it?

# Find out more about each of the methods used below by changing the name of the method
help(str.strip)

s = ' Humpty Dumpty sat on the wall '
print(s)
s = s.strip()
print(s)

print(s.upper())
print(s.lower())

print(s.count("u"))
print(s.count("U"))

print(s.find('sat'))
print(s.find('t', 12))
print(s.find('q', 12))

print(s.replace('sat on', 'fell off'))

words = s.split()    # This returns a list, which we will talk about later.
for word in words:   # But you can iterate over each word in this manner
    print(word.capitalize())

print('-'.join(words))


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
Can you print 'banana' in reverse ('ananab')?
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
Can you print the following? Try using both positive and negative indices.

make a new string containing your first name and print its first letter
print the number of letters in your name
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
Can you rewrite the code below using an f-string?
Can you write Python code for it?

name = "Bruce Banner"
alterego = "The Hulk"
colour = "green"
country = "the USA"
birth_year = 1969
current_year = 2017

print("His name is " + name + " and his alter ego is " + alterego +
      ", a big " + colour + " superhero from " + country + ". He was born in " + str(birth_year) +
      ", so he must be " + str(current_year - birth_year - 1) + " or " + str(current_year - birth_year) +
      " years old now.")


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
Chapter 3 - Strings
This notebook uses code snippets and explanations from this course.
In this notebook, we will focus on the datatype strings. The first thing you learned was printing a simple sentence: "Hello, world!" This sentence, as any other text, was stored by Python as a string. Here are some reasons why strings are important:

Text is usually represented as a string. Text analysis is the ofcus of our course, so we will be dealing with strings a lot.
Strings are also used when reading in files: We tell python which file to open by giving it a filepath, e.g. '../Data/books/HuckFinn.txt'. Don't worry about this for now, we will explain it in block 3

At the end of this chapter, you will be able to:

define strings and understand their internal representation
understand strings as sequences
use character indices for string slicing
combine strings through printing, concatenation and insertion
compare strings using comparison operators and the in operator
understand strings as immutable objects
work with and understand string methods
understand the difference between args and kwargs

If you want to learn more about these topics, you might find the following links useful:

Documentation: String methods
Documentation: Literal String Interpolation (f-strings)
Explanation: Strings
Explanation: F-strings
Video: Strings - working with text data
Video: Strings
Video: String Indexing and Slicing

If you have questions about this chapter, please contact us (cltl.python.course@gmail.com).
1. Defining and representing strings
A string is a sequence of letters/characters which together form a whole (for instance a word, sentence or entire text). In Python, a string is a type of object for which the value is enclosed by single or double quotes. Let's define a few of them:
Can you write Python code for it?

# Here are some strings:
string_1 = "Hello, world!"
string_2 = 'I ❤ cheese'      # If you are using Python 2, your computer will not like this.
string_3 = '1,2,3,4,5,6,7,8,9'


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
Exercise 3:
Can you print all a's in the word 'banana'?
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
How would you print the same sentence using ","?
Can you write Python code for it?

name = "Bruce Banner"
alterego = "The Hulk"
colour = "Green"
country = "USA"

print("His name is" + name + "and his alter ego is" + alterego +
      ", a big" + colour + "superhero from the" + country + ".")


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
In addition to using + to concatenate strings, we can also use the multiplication sign * in combination with an integer for repeating strings (note that we again need to add a blank after 'apples' if we want it to be inserted):
Can you write Python code for it?

my_string = "apples " * 5
print(my_string)


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
Internally, these strings are equally represented. We can check that with the double equals sign, which checks if two objects are the same:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
It's important to note that string methods only return the result. They do not change the string itself.
Can you write Python code for it?

x = 'test'    # Defining x.
y = x.upper() # Using x.upper(), assigning the result to variable y.
print(y)      # Print y.
print(x)      # Print x. It is unchanged.


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
Luckily, there is a way to make the code a lot more easy to understand and nicely formatted. In Python, you can use a
string formatting mechanism called Literal String Interpolation. Strings that are formatted using this mechanism are called f-strings, after the leading character used to denote such strings, and standing for "formatted strings". It works as follows:
Can you write Python code for it?

name="Pia"
age=26
country="Austria"
residence = "The Netherlands"
introduction = f"Hello. My name is {name}. I'm {age} years old and I'm from {country}, but I live in {residence}."
introduction


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
Other formatting methods that you may come across include %-formatting and str.format(), but we recommend that you use f-strings because they are the most intuitive.
Using f-strings can be extremely useful if you're dealing with a lot of data you want to modify in a similar way. Suppose you want to create many new files containing data and name them according to a specific system. You can create a kind of template name and then fill in specific information using variables. (More about files later.)
6. String methods
A method is a function that is associated with an object. For example, the string-method lower() turns a string into all lowercase characters, and the string method upper() makes strings uppercase. You can call this method using the dot-notation as shown below:
Can you write Python code for it?

string_1 = 'Hello, world!'
print(string_1)         # The original string.
print(string_1.lower()) # Lowercased.
print(string_1.upper())# Uppercased.


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
Remove all spaces in the sentence using a string method.
Can you write Python code for it?

my_string = "Humpty Dumpty sat on the wall"
# your code here


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
So from this we can conclude that multiline_text_1 has the same hidden characters (in this case \n, which stands for 'new line') as multiline_text_2. You can show that this is indeed true by using the built-in repr() function (which gives you the Python-internal representation of an object).
Can you write Python code for it?

# Show the internal representation of multiline_text_1.
print(repr(multiline_text_1))
print(repr(multiline_text_2))


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
String concatenation, on the other hand, happens when we merge two strings into a single object using the + operator. No single blanks are inserted, and you cannot concatenate mix types. So, if you want to merge a string and an integer, you will need to convert the integer to a string.
Can you write Python code for it?

number = 5
print("I have " + str(number) + " apples")


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
The \n or newline symbol indicates that we want to start the rest of the text on a new line in the string, the following \ indicates that we want the string to continue on the next line of the code. This difference can be quite hard to understand, but best illustrated with an example where we do not include the \n symbol.
Can you write Python code for it?

long_string = "A very long string \
can be split into multiple \
sentences by appending a backslash \
to the end of the line."

print(long_string)


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
We can also use the escape character "\" in front of the quote, which will tell Python not to treat this specific quote as the end of the string.
Can you write Python code for it?

restaurant = 'Wendy\'s'
print(restaurant)
restaurant = "Wendy\"s"
print(restaurant)


I am working on the file "Chapters-colab/Chapter_03_Strings.ipynb".
The first task is:
What do the methods startswith() and endswith() do? Try them out below.
Can you write Python code for it?

# find out what startswith() and endswith() do


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
1.1 Comparison operators
Here is a list of comparison operators used in Boolean expressions:
(You have already used these operators in the previous chapters, but we are treating them in more detail here.)
| Operator | Meaning | True | False |
|-----------|--------|--------|--------|
| == |    equal    | 2 == 2 | 2 == 3 |
| != |    not equal   | 3 != 2 | 2 != 2 |
| < | less than | 2 < 13  | 2 < 2 |
| <= |    less than or equal to   |  2 <= 2 | 3 <= 2  |
| > | greater than     | 13 > 2  | 2 > 13  |
| >= |    greather than or equal to   |  3 >= 3  | 2 >= 3  |
Remember that the single = is reserved for assignment! Boolean expressions look at variables but never change them.
Can you write Python code for it?

print(2 < 5)
print(2 <= 5)
print(3 > 7)
print(3 >= 7)
print(3 == 3)
print("school" == "school")
print("Python" != "SPSS")


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
1.2 Membership operators
Python also has so-called membership operators:
| Operator | function | True | False |
|-----------|--------|--------|--------|
| in | left object is a member of right object | "c" in "cat" | "f" in "cat" |
| not in |left object is NOT a member of right object |  "f"  not in "cat" | "c" not in "cat" |
We have already seen the operator in being used for checking whether a string (single or multiple characters) is a substring of another one:
Can you write Python code for it?

print("fun" in "function")
print("pie" in "python")


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
1.3 And, or, and not
Finally, boolean operations are often performed using the boolean operators and, or and not. Given two boolean expressions, bool1 and bool2, this is how they work:
| operation | function | True | False |
|-----------|--------|----------|---------|
| bool1 and bool2 | True if both bool1 and bool2 are True, otherwise False | (5 == 5 and 3 < 5) | (5 == 5 and 3 > 5) |
| bool1 or bool2 |    True when at least one of the boolean expressions is True, otherwise False    |  (5 == 5 or 3 > 5) | (5 != 5 or 3 > 5) |
| not bool1 | True if bool1 is False, otherwise False | (not 5 != 5) | (not 5 == 5) |
Here are some examples of and:
Can you write Python code for it?

letters = ['a','b','c','d']
numbers = [1,2,3,4,5]

print('a' in letters and 2 in numbers)

print("z" in letters and 3 in numbers)

print("f" in letters and 0 in numbers)


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
1.4 EXTRA: all() and any()
Take a look at the following example. Do you think it is clear?
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
Chapter 4 - Boolean Expressions and Conditions
This notebook uses code snippets and explanations from this course.
So far, we have learned how to use Python as a basic calculator and how to store information in variables. Now we will set the first steps to an actual useful program. A lot of programming has to do with executing code if a particular condition holds. This enables a program to act upon its inputs. For example: an app on your phone might give a warning if the battery level is lower than 5%. This means that the program needs to check if the variable battery_level is lower than the value of 5. We can do these checks using so called Boolean expressions. These Boolean expressions are the main element in probably one of the most used things in Python: if statements.
At the end of this topic, you will be able to:

work with and understand boolean expressions
work with and understand if statements
understand what indentation is
understand what nesting is

If you want to learn more about these topics, you might find the following links useful:

Documentation: Built-in Types (boolean expressions)
Video: Python Booleans
Video: Conditionals
Explanation: if elif else

If you have questions about this chapter, please contact us(cltl.python.course@gmail.com)**.
1. Boolean expressions
A Boolean expression (or simply: boolean) is an expression that results in the type bool in Python. Possible values are either True or False. Boolean expressions are the building blocks of programming. Any expression that results in True or False can be considered a Boolean expression.
So far you've mainly seen:
Can you write Python code for it?

print(type('this is a string'))
print(type(101))
print(type(0.8))


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
Exercise 2:
Write a small program that defines a variable weight. If the weight is > 50 pounds, print "There is a $25 charge for luggage that heavy." If it is not, print: "Thank you for your business." If the weight is exactly 50, print: "Pfiew! The weight is just right!". Change the value of weight a couple of times to check whether your code works. Make use of the logical operators and the if-elif-else construct!
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
Exercise 4:
Can you rewrite the code below without nesting? Hint: use the if-elif-else construct.
Can you write Python code for it?

x = float(input("Enter a number: "))
if x >= 0:
    if x == 0:
        print("Zero")
    else:
        print("Positive number")
else:
    print("Negative number")


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
Exercise 5:
A friend wants your advice on how much oranges he should buy. Write a program that will give the advice to buy 24 oranges if the price is lower than 1.50 EUR per kg, 12 oranges if the price is between 1.50 EUR and 3 EUR, and only 1 orange if the price is higher than 3 EUR. But also tell him that he should only buy them if the oranges are fresh; otherwise, he should not get any. Use nesting and the if-elif-else construct.
Can you write Python code for it?

orange_quality = "fresh"
orange_price = 1.75
# your code here


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
Exercises
Exercise 1:
It's important to practice a lot with boolean expressions. Here is a list of them, which orginate from learnpythonthehardway. Try to guess the output.
Can you write Python code for it?

print(True and True)

print(False and True)

print(1 == 1 and 2 == 1)

print("test" == "test")

print(1 == 1 or 2 != 1)

print(True and 1 == 1)

print(False and 0 != 0)

print(True or 1 == 1)

print("test" == "testing")

print(1 != 0 and 2 == 1)

print("test" != "testing")

print("test" == 1)

print(not (True and False))

print(not (1 == 1 and 0 != 1))

print(not (10 == 1 or 1000 == 1000))

print(not (1 != 10 or 3 == 4))

print(not ("testing" == "testing" and "Zed" == "Cool Guy"))

print(1 == 1 and (not ("testing" == 1 or 1 == 0)))

print("chunky" == "bacon" and (not (3 == 4 or 3 == 3)))

print(3 == 3 and (not ("testing" == "testing" or "Python" == "Fun")))

print("test" != "testing" and 1 == 1 and 2 == 2 and 20 in [1, 20, 3, 4,5])


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
Here are some examples of any():
Can you write Python code for it?

list_bools3 = ['f' in letters,
                200 in numbers]
print(list_bools3)
boolean_expression3 = any(list_bools3)
print(boolean_expression3)

list_bools4 = ['a' in letters,
               20 in numbers,
               2 in numbers]
print(list_bools4)
boolean_expression4 =  any(list_bools4)
print(boolean_expression4)


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
Here are some examples of or:
Can you write Python code for it?

letters = ['a','b','c','d']
numbers = [1,2,3,4,5]

print('f' in letters or 2 in numbers)

print('a' in letters or 2 in numbers)

print('f' in letters or 10 in numbers)


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
However, we can use membership operators with other types of 'containers', such as lists. We will discuss lists in much more detail later on, but they represent ordered sequences of objects like strings, integers or a combination. We can use in and not in to check whether an object is a member of a list:
Can you write Python code for it?

letters = ['a','b','c','d']
numbers = [1,2,3,4,5]
mixed = [1,2,3,'a','b','c']

print('a' in letters)

print('g' not in letters)

print('d' in mixed)

print(1 in numbers)

print(3 not in mixed)

print('a' not in 'hello world')


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
Let's look at some examples. Try to guess the output based on the information about the operators in the table above. Hence, will the expression result in True or False in the following examples?
Can you write Python code for it?

print(5 == 5)

print(5 == 4)

print(10 < 20)

print(10 < 8)

print(10 < 10)

print(10 <= 10)

print(20 >= 21)

print(20 == 20)

print(1 == '1')

print(1 != 2)

boolean_expression = 5 == 4
print(boolean_expression)


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
Note that for some of these, there are alternative ways of writing them. For example, 'x not in y' and 'not x in y' are identical, and so are 'not x == y' and 'x != y'. For now, it does not really matter which one you use. If you want to read more about it, have a look here and here.
Can you write Python code for it?

print(not 'x' in letters)
print('x' not in letters)

print(not 4 == 4)
print(4 != 4)


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
Now Python always runs one of the two pieces of code. It's like arriving at a fork in the road and choosing one path to follow.
2.2 Multi-way decisions
But of course we don't have to stop there. If you have multiple options, you can use the elif statement. For every if block, you can have one if statement, multiple elif statements and one else statement. So now we know the entire if-elif-else construct:
Can you write Python code for it?

age = 21
if age < 12:
    print("You're still a child!")
elif age < 18:
    print("You are a teenager!")
elif age < 30:
    print("You're pretty young!")
else:
    print("Wow, you're old!")


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
Now we're introducing:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
What's wrong in the following code? Correct the mistake.
Can you write Python code for it?

my_string = "hello"
if my_string == "hello"
    print("world")


I am working on the file "Chapters-colab/Chapter_04_Boolean_Expressions_and_Conditions.ipynb".
The first task is:
You can use as many if statements as you like:
Can you write Python code for it?

number = 5
if number == 5:
    print("number equals 5")
if number > 4:
    print("number is greater than 4")
if number >= 5:
    print("number is greater than or equals 5")
if number < 6:
    print("number is less than 6")
if number <= 5:
    print("number is less than or equals 5")
if number != 6 :
    print("number does not equal 6")


I am working on the file "Chapters-colab/Chapter_05_Core_concepts_of_containers.ipynb".
The first task is:
2. Understanding class methods
Let's look at some string method examples from the last chapters:
Can you write Python code for it?

a_string = 'hello world'
print('example 1. upper method:', a_string.upper())
print('example 2. count method:', a_string.count('l'))
print('example 3. replace method:', a_string.replace('l', 'b'))
print('example 4. split method:', a_string.split())
print('example 5. split method:', a_string.split(sep='o'))


I am working on the file "Chapters-colab/Chapter_05_Core_concepts_of_containers.ipynb".
The first task is:
Exercise 2:
Please illustrate the difference between positional and keyword parameters using the example of string methods. Feel free to use dir(str) and the help function for inspiration.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_05_Core_concepts_of_containers.ipynb".
The first task is:
For the answer, we need to go back to the function parameters:
* replace: replace(self, old, new, count=-1, /)
* split: split(self, /, sep=None, maxsplit=-1)
Please note that the difference is that count is to the left of the forward slash, and sep and maxsplit are to the right of the forward slash! We can call any parameter to the right of the forward slash using the name of the parameter. For any parameter to the left of the forward slash, we can only provide the value.
This does work:
Can you write Python code for it?

a_string = 'rats are the best.'
result = a_string.replace('r', 'c', 1)
print(result)


I am working on the file "Chapters-colab/Chapter_05_Core_concepts_of_containers.ipynb".
The first task is:
In all of the examples above, a string method is called, e.g., upper or count.
However, they differ regarding their arguments:
* There are no arguments in the case of upper, i.e., no arguments between the round brackets.
* for count, we specify a string 'l' as an argument
* for replace, we specify two strings as arguments
* for split, we can specify an argument, but we do not have to
This might look a bit confusing. Luckily Python has a built-in function help, which provides us insight into how to use each method. We will guide you through understanding the information provided for the string method replace.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_05_Core_concepts_of_containers.ipynb".
The first task is:
It worked! We've called the string method by only providing a value for the positional parameters. However, what if we are not happy with the provided default value, can we override it?
Let's try this. The keyword parameter count allows us to indicate how many times to replace a substring. Let's try to only replace 'r' to 'c' one time.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_05_Core_concepts_of_containers.ipynb".
The first task is:
Let's go through the parameters of the string method split:
* self: for now, the only thing to remember about self is that it tells you that replace is a method and that you should ignore it in calling the method!
* / (forward slash): for now, please ignore, we will come back to this.
* sep=None: this is a keyword parameter, meaning that it has a default value, i.e., None.
* maxsplit=-1: this is a keyword parameter, by which you can indicate how many times to split.
Since split has no positional parameters, we should be able to call the method without providing arguments.
Can you write Python code for it?

a_string = 'USA Today has come out with a new survey: Apparently three out of four people make up 75 percent of the population.'
words = a_string.split()
print(words)


I am working on the file "Chapters-colab/Chapter_05_Core_concepts_of_containers.ipynb".
The first task is:
Please note that we have splitted the string on a space ' ' two times.
Try and play with with the split function: (e.g. how does split(' ') differ from split()?)
2.1 The forward slash
So far, we have not explained the forward slash in the parameters. Here, we highlight its importance to calling a method. We show two examples. The main question is the following: why is the first call successful, and why does the second call result in error?
Can you write Python code for it?

a_string = 'USA Today has come out with a new survey: Apparently three out of four people make up 75 percent of the population.'
words = a_string.split(sep=' ', maxsplit=2)
print(words)

a_string = 'rats are the best.'
result = a_string.replace('r', 'c', count=1)


I am working on the file "Chapters-colab/Chapter_05_Core_concepts_of_containers.ipynb".
The first task is:
This does not.
Can you write Python code for it?

a_string = 'rats are the best.'
result = a_string.replace('r', 'c', count=1)


I am working on the file "Chapters-colab/Chapter_05_Core_concepts_of_containers.ipynb".
The first task is:
Yes! We've provided a value for count, e.g., 1, and now 'r' is only replaced once with 'c'. Luckily, the 'r' in 'are' has not been replaced.
We will now move on to the string method split.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
3. How to extract/inspect items in a list
Please note that indexing and slicing work the same way as with strings. You have already seen indexing for the characters in a string. Every item in the list has hence its index number. We start counting at 0! The indices for our
list ['John', 'Bob', 'Marry'] are as follows:
John|Bob|Mary
---|---|--|
0|1|2|
-3|-2|-1
You can access elements in a list just as you can access characters in a string by using the index.
Can you write Python code for it?

fruit_basket = ['apple', 'banana', 'cherry']
fruit = 'banana'

print(fruit_basket[1])
print(fruit[1])


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
4. Basic List Operations
Python allows at least the following very useful list operations:
* concatenation
* repetition
* membership
* comparison
The '+' sign concatenates two lists:
Can you write Python code for it?

one_list = ['where', 'is']
another_list = ['the', 'rest', '?']
print(one_list + another_list)


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
5. Use built-in functions on lists
Python has a range of functions that operate on lists. We can easily get some simple calculations done with these functions:
Can you write Python code for it?

nums = [3, 41, 12, 9, 74, 15]
print(len(nums)) # number of items in a list
print(max(nums)) # highest value in a list
print(min(nums)) # lowest value in a list
print(sum(nums)) # sum of all values in a list


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
And we can extract one part of a list using slicing:
Can you write Python code for it?

friend_list = ['John', 'Bob', 'Marry']
list_with_fewer_friends = friend_list[:2]
print(list_with_fewer_friends)


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
Chapter 6 - Lists
This notebook uses code snippets and explanations from this course.
As we have learned before, strings and integers have one value in them. When we put a new value in them, the old value is overwritten. In this chapter, we will have a first look at containers. A container allows us to put many values in a single box. A container is nice because we can carry lots of values around in one convenient package. It is very straightforward to store a list of items as a container. Not surprisingly, we call this a list.
At the end of this chapter, you will be able to:
* create a list
* add items to a list
* extract/inspect items in a list
* perform basic list operations
* use built-in functions on lists
If you want to learn more about these topics, you might find the following links useful:
* Python documentation
* Tutorial on lists
* Another tutorial on lists
If you have questions about this chapter, please us (cltl.python.course@gmail.com).
1. How to create a list
It's straightforward to create a list. Please look at the following examples:
Can you write Python code for it?

friends = ['John', 'Bob', 'Mary']
stuff_to_pack = ['socks','shirt','toothbrush']
print(friends)
print(stuff_to_pack)


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
Exercise 2:
Please count how many times John occurs in the list
Can you write Python code for it?

friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']

#  your code here


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
Exercise 3:
Please use a built-in function to determine the number of strings in the list below
Can you write Python code for it?

friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']

# your code here


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
Exercise 4:
Please add world to the string and the list below. Only create a new object if it is necessary.
Can you write Python code for it?

a_string = 'hello'
a_list = ['hello']

# your code here


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
If you insert an index that is higher than what is present in the list, you will get an IndexError:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
In order to have a complete overview of all list methods, you can use the dir built-in function:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
Of course, you can use lists in membership boolean expressions
Can you write Python code for it?

life = ['a', 'lot', 'of', 'stuff']
print('meaning' in life)


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
Square brackets surround lists, and commas separate the elements in the list
A list element can be any Python object - even another list
A list can be empty
Can you write Python code for it?

#list of integers
print([1, 24, 76])

#list of strings
print(['red', 'yellow', 'blue'])

#mixed list
print(['red', 24, 98.6])

#list with a list included
print([1, [5, 6], 7])

#empty list
print([])


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
The index method has one positional parameter value, and two keyword parameters, and returns the first index of the value. It is hence similar to the count method, but now the first index is returned of the value instead of the count.
Can you write Python code for it?

friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']
first_index_with_john = friend_list.index('Bob')
print(first_index_with_john)


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
The reason why the first example is the correct one is that lists are mutable, which means that you can change the contents of a list. You can hence change the items in a list without assigning it to a new variable.
In comparison, when we want to change an immutable object like a string, the method returns a copy of the input:
Can you write Python code for it?

help(str.replace)

a_string = 'hello'
a_string.replace('l', 'b')
print(a_string) # a_string has not been changed

a_string = 'hello'
a_new_string = a_string.replace('l', 'b')
print(a_string)
print(a_new_string)


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
Two additional methods are useful for inspecting lists:
* count
* index
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
We can hence use this index number to extract items from a list (just as with strings).
Can you write Python code for it?

friend_list = ['John', 'Bob', 'Marry']
print(friend_list[0])
print(friend_list[1])
print(friend_list[2])


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
We get a ValueError when the value is not in the list.
Can you write Python code for it?

friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']
friend_list.index('Frank')


I am working on the file "Chapters-colab/Chapter_06_Lists.ipynb".
The first task is:
We learn that append has one positional parameter object. Remember that you should ignore 'self' (it just means that append is a list method). append returns None. It might be a bit confusing at first that a list method returns None. Please carefully look at the difference between the two following examples. Please predict what will be printed in each code snippet below:
Can you write Python code for it?

a_list = [1, 3, 4]
a_list.append(5)
print(a_list)

a_list = [1, 3, 4]
a_list = a_list.append(5)
print(a_list)


I am working on the file "Chapters-colab/Chapter_07_Sets.ipynb".
The first task is:
2. How to add items to a set
The most common way of adding an item to a set is by using the add method. The add method has one positional parameter, namely what you are going to add to the set, and it returns None.
Can you write Python code for it?

a_set = set()
a_set.add(1)
print(a_set)

a_set = set()
a_set = a_set.add(1)
print(a_set)


I am working on the file "Chapters-colab/Chapter_07_Sets.ipynb".
The first task is:
4. Using built-in functions on sets
The same range of functions that operate on lists also work with sets. We can easily get some simple calculations done with these functions:
Can you write Python code for it?

nums = {3, 41, 12, 9, 74, 15}
print(len(nums)) # number of items in a set
print(max(nums)) # highest value in a set
print(min(nums)) # lowest value in a set
print(sum(nums)) # sum of all values in a set


I am working on the file "Chapters-colab/Chapter_07_Sets.ipynb".
The first task is:
5. An overview of set operations
There are many more operations which we can perform on sets. Here is an overview of some of them.
In order to get used to them, please call the help function on each of them (e.g., help(set.union)). This will give you the information about the positional parameters, keyword parameters, and what is returned by the method.
Can you write Python code for it?

set_a = {1, 2, 3}
set_b = {4, 5, 6}
an_element = 4

print(set_a)

#do some operations
set_a.add(an_element)  # Add an_element to set_a
print(set_a)
set_a.update(set_b)     # Add the elements of set_b to set_a
print(set_a)
set_a.pop()         # Remove and return an arbitrary set element. How does this compare to the list method pop?
print(set_a)
set_a.remove(an_element)     # Remove an_element from set_a
print(set_a)


I am working on the file "Chapters-colab/Chapter_07_Sets.ipynb".
The first task is:
Before diving into some exercises, you may want to the dir built-in function again to see an overview of all set methods:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_07_Sets.ipynb".
The first task is:
Exercises
Exercise 1:
Please create an empty set and use the add method to add four items to it: 'a', 'set', 'is', 'born'
Exercise 2:
Please use a built-in method to count how many items your set has
Exercise 3:
How would you remove one item from the set?
Exercise 4:
Please check which items are in both sets:
Can you write Python code for it?

set_1 = {'just', 'some', 'words'}
set_2 = {'some', 'other', 'words'}
# your code here


I am working on the file "Chapters-colab/Chapter_07_Sets.ipynb".
The first task is:
Python shows dots (...) for the parameters of the union method. Based on the docstring, we learn that we can provide any number of sets, and Python will return the union of them.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_07_Sets.ipynb".
The first task is:
Since sets are unordered, you can not use an index to extract an element from a set.
Can you write Python code for it?

a_set = set()
a_set.add(1)
a_set.add(2)
a_set[0]


I am working on the file "Chapters-colab/Chapter_07_Sets.ipynb".
The first task is:
The intersection method has works in a similar manner as the union method, but returns a new set containing only the intersection of the sets.
Can you write Python code for it?

help(set.intersection)

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
the_intersection = set1.intersection(set2)
print(the_intersection)

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = {5, 8, 9, 10}
the_intersection = set1.intersection(set2, set3)
print(the_intersection)


I am working on the file "Chapters-colab/Chapter_07_Sets.ipynb".
The first task is:
This also means that you can check if two sets are the same even if you don't know the order in which items were put in:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_07_Sets.ipynb".
The first task is:
You observe that there are many methods defined for sets! Here we explain the two most common methods. We start with the union method.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_08_Comparison_of_lists_and_sets.ipynb".
The first task is:
And this will usually be relatively quick:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_08_Comparison_of_lists_and_sets.ipynb".
The first task is:
Is it possible to understand the order of items in a set? Yes, but we will not cover it here since it is not important for the tasks we cover.
What is then the take home message about order? The answer is: you have it for lists, but not for sets.
If you want to learn more about this, look up the data structure called hash table (https://en.wikipedia.org/wiki/Hash_table)
1.3 Finding element(s)
It's usually quicker to check if an element is in a set than to check if it is in a list.
Hence, this will be usally relatively slow:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_08_Comparison_of_lists_and_sets.ipynb".
The first task is:
Is it possible to understand the speed of finding elements of items in sets and lists? Yes, but we will not cover it here since it is not important for the tasks we cover.
What is then the take home message about speed? The answer is: it's probably quicker to use sets.
1.4 Mutability of elements in can contain
sets can only contain immutable objects.
This works:
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_08_Comparison_of_lists_and_sets.ipynb".
The first task is:
This as well
Can you write Python code for it?

a_list = []
a_list.append([1])
print(a_list)


I am working on the file "Chapters-colab/Chapter_08_Comparison_of_lists_and_sets.ipynb".
The first task is:
Tip
You can create a set from a list. Attention: duplicates will be removed.
Can you write Python code for it?

a_list = [1,2,3,4, 4]

a_set = set(a_list)

print(a_list)
print(a_set)


I am working on the file "Chapters-colab/Chapter_08_Comparison_of_lists_and_sets.ipynb".
The first task is:
lists can contain any Python object.
This works:
Can you write Python code for it?

a_list = []
a_list.append(1)
print(a_list)


I am working on the file "Chapters-colab/Chapter_09_Looping_over_containers.ipynb".
The first task is:
2. Looping over a set
It is also possible to loop over a set
Can you write Python code for it?

a_set = {'sets', 'are', 'unordered'}
for item in a_set:
    print(item)


I am working on the file "Chapters-colab/Chapter_09_Looping_over_containers.ipynb".
The first task is:
5. Unpacking variables
It's possible to unpack tuples to separate variables
Can you write Python code for it?

a_tuple = (1, 'a', 2)
first_el, second_el, third_el = a_tuple
print(first_el)
print(second_el)
print(third_el)


I am working on the file "Chapters-colab/Chapter_09_Looping_over_containers.ipynb".
The first task is:
6. Continue and break
break
The break statement lets us escape a loop.
Can you write Python code for it?

word = "hippopotamus"

for letter in word:
    print(letter)
    if letter =="o":
        break


I am working on the file "Chapters-colab/Chapter_09_Looping_over_containers.ipynb".
The first task is:
A tuple can be empty. You can use () or tuple():
Can you write Python code for it?

an_empty_tuple = ()
print(an_empty_tuple)

another_empty_tuple = tuple()
print(another_empty_tuple)


I am working on the file "Chapters-colab/Chapter_09_Looping_over_containers.ipynb".
The first task is:
Exercise 2:
We have a collection of numbers and want to know how many unique numbers we have. Then we want to print each of them on a single line using a single print statment and not using '\n' to stat a new line.
Can you write Python code for it?

number_collection = [1,2,2,3,50, 50, 60, 57, 58, 3, 37, 37]
unique_number = # your code here

# print each number on a single line
# your code here


I am working on the file "Chapters-colab/Chapter_09_Looping_over_containers.ipynb".
The first task is:
Exercise 3:
Why might unpacking lists in this way sometimes be a bad idea?
Hint: Think of mutability and consider the code below.
Can you write Python code for it?

a_list = [1,2,3]
first_el, second_el, third_el = a_list
print(first_el)
print(second_el)
print(third_el)

a_list.append(5)
first_el, second_el, third_el = a_list
print(first_el)
print(second_el)
print(third_el)

a_list.append(5)
first_el, second_el, third_el = a_list
print(first_el)
print(second_el)
print(third_el)


I am working on the file "Chapters-colab/Chapter_09_Looping_over_containers.ipynb".
The first task is:
Loops work extremely well with if-statements
Can you write Python code for it?

for item in ['Python', 'is', 'really', 'nice', 'right?']:
    if item.startswith('r'):
        print(item, 'startswith the letter r')
    else:
        print(item, 'does not start with the letter r')


I am working on the file "Chapters-colab/Chapter_09_Looping_over_containers.ipynb".
The first task is:
This loop prints the numbers 1, 2, and 3, each on a new line. The variable name number is just something I have chosen. It could have been anything, even something like sugar_bunny. But number is nice and descriptive.
OK, so how does the loop work?

The Python interpreter starts by checking whether there's anything to iterate over. If the list is empty, it just passes over the for-loop and does nothing.
Then, the first value in the iterable (in this case a list) gets assigned to the variable number.
Following this, we enter a for-loop context, indicated by the indentation (four spaces preceding the print function). This for-loop context can be as big as you want. All Python cares about is those four spaces. Everything that is indented is part of the for-loop context.
Then, Python carries out all the operations in the for-loop context. In this case, this is just print(number). Because number refers to the first element of the list, it prints 1.
Once all operations in the for-loop context have been carried out, the interpreter checks if there are any more elements in the list. If so, the next value (in this case 2) gets assigned to the variable number.
Then, we move to step 3 again: enter the for-loop context, carry out all the operations, and check if there's another element in the list, and so on, until there are no more elements left.

Please note that if a container (in this case a list) is empty, we will not print anything.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_09_Looping_over_containers.ipynb".
The first task is:
a tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets.
the elements of a tuple have a defined order, just like a list.
tuples can contain immutable objects.
tuples can contain mutable objects, but we would advise you not to use sets and lists in tuples
items cannot be added or removed (with some exceptions which are not important here)
a tuple can be empty
tuples have two methods: index and count

Important for use
* you can unpack tuples
* tuples are often used with for-loops
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_09_Looping_over_containers.ipynb".
The first task is:
continue
The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration.
Can you write Python code for it?

word = "hippopotamus"

for letter in word:
    if letter =="o":
        continue
    print(letter)


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
3. How to add items to a dictionary
There is one very simple way in order to add a key:value pair to a dictionary. Please look at the following code snippet:
Can you write Python code for it?

a_dict = dict()
print(a_dict)

a_dict['Frank'] = 8
print(a_dict)


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
5. Counting with a dictionary
Dictionaries are very useful to derive statistics. For example, we can easily determine the frequency of each letter in a word.
Can you write Python code for it?

letter2freq = dict()
word = 'hippo'

for letter in word:

    if letter in letter2freq: # add 1 to the dictionary if the keys exists
        letter2freq[letter] += 1 # note: x +=1 does the same as x = x + 1
    else:
        letter2freq[letter] = 1 # set default value to 1 if key does not exists

    print(letter, letter2freq)

print()
print(letter2freq)


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
Exercise 3:
Use a loop and unpacking to print the items and numbers on your shopping list in the following format:
Item: [Item], number: [number]
e.g. Item: tomatoes, number: 3
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
Feel free to start using this module after the assignment of this block.
6. Nested dictionaries
Since dictionaries consists of key:value pairs, we can actually make another dictionary the value of a dictionary.
Can you write Python code for it?

a_nested_dictionary = {'a_key':
                       {'nested_key1': 1,
                        'nested_key2': 2,
                        'nested_key3': 3}
                      }
print(a_nested_dictionary)


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
However, you're not happy about the solution. Every time you request a grade, we need to
first determine the position of the student in the list and then use that index + 1 to obtain the grade.  That's pretty inefficient. The take-home message here is that lists are not really good if we want two pieces of information together. Dictionaries for the rescue!
Can you write Python code for it?

student_grades = {'Frank': 8, 'Susan': 7, 'Guido': 10}

student_grades['Frank']


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
If the key is not in the dictionary, it will return a KeyError.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
In order to access the nested value, we must do a look up for each key on each nested level
Can you write Python code for it?

the_nested_value = a_nested_dictionary['a_key']['nested_key1']
print(the_nested_value)


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
Please note that a dictionary can be empty (use dict()):
Can you write Python code for it?

an_empty_dict = dict()
another_empty_dict = {} # This works too, but it is less readable and confusing (looks similar to sets)
print(type(another_empty_dict), type(an_empty_dict))


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
Please note that dictionary keys should be unique identifiers for the values in the dictionary.  Key:value pairs get overwritten if you assign a different value to an existing key.
Can you write Python code for it?

a_dict = dict()
a_dict['Frank'] = 8
print(a_dict)
a_dict['Frank'] = 7
print(a_dict)
a_dict['Frank'] = 9
print(a_dict)


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
Please note that the values in a dictionary can by any python object
This works (integers as values)
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
Practice questions:
What do sets and dictionaries have in common?
What do lists and tuples have in common?
Can you add things to a list?
Can you add things to a tuples?

An overview:
| property                       | set               | list            | tuple       | dict keys | dict values |
|------------------------------- |-------------------|-----------------|-------------|-----------|-------------|
| mutable (can you add add/remove?) | yes        | yes             | no          | yes       | yes         |
| can contain duplicates     | no                | yes             | yes         | no        | yes            |
| ordered                    | no                | yes             | yes         | yes, but do not rely on it          | depends on type of value         |
| finding element(s)         | quick             | slow            | slow        | quick             | depends on type of value         |
| can contain                | immutables | all     | all | immutables  |  all           |
Exercises
Exercise 1:
You are tying to keep track of your groceries using a python dictionary. Please add 'tomatoes', 'bread', 'chocolate bars' and 'pineapples' to your shopping dictionary and assign values according to how many items of each you would like to buy.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
The items method returns a list of tuples. We can combine what we have learnt about looping and tuples to access the keys (the students' names) and values (their grades):
Can you write Python code for it?

for key, value in student_grades.items(): # please note the tuple unpacking
    print(key, value)


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
This also makes it possible to detect which students obtained a grade of 8 or higher.
Can you write Python code for it?

for student, grade in student_grades.items():
    if grade > 7:
        print(student, grade)


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
This does not (list as keys)
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
We can use the built-in functions to inspect the keys and values. For example:
Can you write Python code for it?

the_values = student_grades.values()
print(len(the_values)) # number of values in a dict
print(max(the_values)) # highest value of values in a dict
print(min(the_values)) # lowest value of values in a dict
print(sum(the_values)) # sum of all values of values in a dict


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
a dictionary is surrounded by curly brackets, and the key/value pairs are separated by commas.
A dictionary consists of one or more key:value pairs. The key is the 'identifier' or "name" that is used to describe the value.
the keys in a dictionary are unique
the syntax for a key/value pair is: KEY : VALUE
the keys (e.g. 'Frank') in a dictionary have to be immutable
the values (e.g., 8) in a dictionary can by any python object
a dictionary can be empty

Please note that keys in a dictionary have to immutable.
This works (strings as keys)
Can you write Python code for it?

student_grades = {'Frank': 8, 'Susan': 7, 'Guido': 10}


I am working on the file "Chapters-colab/Chapter_10_Dictionaries.ipynb".
The first task is:
the keys method returns the keys in a dictionary
Can you write Python code for it?

student_grades = {'Frank': 8, 'Susan': 7, 'Guido': 10}

the_keys = student_grades.keys()
print(the_keys)


I am working on the file "Chapters-colab/Chapter_11_Functions_and_scope.ipynb".
The first task is:
1.3.2 Calling a function from within another function
We can also define functions that call other functions, which is very helpful if we want to split our task into smaller, more manageable subtasks:
Can you write Python code for it?

def new_line():
    """Print a new line."""
    print()

def two_new_lines():
    """Print two new lines."""
    new_line()
    new_line()

print("Printing a single line...")
new_line()
print("Printing two lines...")
two_new_lines()
print("Printed two lines")