I am working on the file "Chapters-colab/Chapter_20_Visualization_and_Statistics.ipynb".
The first task is:
It's also apt to call this a 'Thought-starter'. Not all visualizations in this diagram are frequently used; but also there are many great kinds of visualizations that aren't in this diagram. To get some more inspiration, check out the example galleries for these libraries:

D3.js
Seaborn
Bokeh
Pandas
Matplotlib
Vis.js

But before you get carried away, do realize that sometimes all you need is a good table. Tables are visualizations, too! For a good guide on how to make tables, read the first three pages of the LaTeX booktabs package documentation. Also see this guide with some practical tips.
1.2. What kind of visualizations not to choose
As a warm-up exercise, take some time to browse wtf-viz. For each of the examples, think about the following questions:

What is the author trying to convey here?
How did they try to achieve this?
What went wrong?
How could the visualization be improved? Or can you think of a better way to visualize this data?
What is the take-home message here for you?

For in-depth critiques of visualizations, see Graphic Violence. Here's a page in Dutch.
1. Introduction to visualization
1.1. What kind of visualization to choose
Visualization has two purposes: aesthethics and informativeness. We want to optimize for both. Luckily, they are somewhat independent, so that should work. Whether something will be a good visualization will be determined by: whether the creator makes the right choices, in the given context, for the given audience and purpose.
The following chart was made by (Abela, 2006). It provides a first intuition on what kind of visualization to choose for your data. He also asks exactly the right question: What do you want to show? It is essential for any piece of communication to first consider: what is my main point? And after creating a visualization, to ask yourself: does this visualization indeed communicate what I want to communicate? (Ideally, also ask others: what kind of message am I conveying here?)
2. Visualization in Python
2.1. A little history
As you've seen in...
Can you write Python code for it?

# This is special Jupyter notebook syntax, enabling interactive plotting mode.
# In this mode, all plots are shown inside the notebook!
# If you are not using notebooks (e.g. in a standalone script), don't include this.
%matplotlib inline
import matplotlib.pyplot as plt


I am working on the file "Chapters-colab/Chapter_20_Visualization_and_Statistics.ipynb".
The first task is:
Look at all those unimodal distributions (with a single peak)!
4.2. A concreteness dataset
We'll work with another data file by Brysbaert and colleagues, consisting of concreteness ratings. I.e. how abstract or concrete participants think a given word is.
Can you write Python code for it?

!ls ../Data | grep c

import csv
# Let's load the data first.
concreteness_entries = []
with open('../Extra_Material/Examples/Flask_Website/static/data/Concreteness_ratings_Brysbaert_et_al_BRM.txt') as f:
    reader = csv.DictReader(f, delimiter='\t')
    for entry in reader:
        entry['Conc.M'] = float(entry['Conc.M'])
        concreteness_entries.append(entry)


I am working on the file "Chapters-colab/Chapter_20_Visualization_and_Statistics.ipynb".
The first task is:
That doesn't look like a super strong correlation. We can check by using the correlation measures from SciPy.
Can you write Python code for it?

# If we're interested in predicting the actual rating.
corr, sig = pearsonr(word_length, rating)
print('Correlation, according to Pearsonr:', corr)

# If we're interested in ranking the words by their concreteness.
corr, sig = spearmanr(word_length, rating)
print('Correlation, according to Spearmanr:', corr)

# Because word length is bound to result in ties (many words have the same length),
# some people argue you should use Kendall's Tau instead of Spearman's R:
from scipy.stats import kendalltau

corr, sig = kendalltau(word_length, rating)
print("Correlation, according to Kendall's Tau:", corr)


I am working on the file "Chapters-colab/Chapter_20_Visualization_and_Statistics.ipynb".
The first task is:
The Spearman correlation is perfect in both cases, because with each increase in X, there is an increase in Y. But because that increase isn't the same at each step, we see that the Pearson correlation is slightly lower.
In Natural Language Processing, people typically use the Spearman correlation because they are interested in relative scores: does the model score A higher than B? The exact score often doesn't matter. Hence Spearman provides a better measure, because it doesn't penalize models for non-linear behavior.
4. Putting it all together: Exploratory visualization and analysis
Before you start working on a particular dataset, it's often a good idea to explore the data first. If you have text data; open the file and see what it looks like. If you have numeric data, it's a good idea to visualize what's going on. This section shows you some ways to do exactly that, on two datasets.
4.1. A dataset with sentiment scores
Here is a histogram plot of sentiment scores for English (from Dodds et al. 2014), where native speakers rated a list of 10,022 words on a scale from 0 (negative) to 9 (positive).
Can you write Python code for it?

# Load the data (one score per line, words are in a separate file).
with open('../Data/Dodds2014/data/labMTscores-english.csv') as f:
    scores = [float(line.strip()) for line in f]

# Plot the histogram
sns.distplot(scores, kde=False);


I am working on the file "Chapters-colab/Chapter_20_Visualization_and_Statistics.ipynb".
The first task is:
This loop processes the dictionary into a format that's easy to send to matplotlib - a list of pizza names (for the labels on the bars) and a list of vote counts (for the actual graph.)
Can you write Python code for it?

names = []
votes = []
# Split the dictionary of names->votes into two lists, one holding names and the other holding vote counts
for pizza in counts:
    names.append(pizza)
    votes.append(counts[pizza])


I am working on the file "Chapters-colab/Chapter_20_Visualization_and_Statistics.ipynb".
The first task is:
We create a range of indexes for the X values in the graph, one entry for each entry in the "counts" dictionary (ie len(counts)), numbered 0,1,2,3,etc. This will spread out the graph bars evenly across the X axis on the plot.
np.arange is a NumPy function like the range() function in Python, only the result it produces is a "NumPy array". We'll see why this is useful in a second.
plt.bar() creates a column graph, using the "x" values as the X axis positions and the values in the votes array (ie the vote counts) as the height of each bar. Finally, we add the labels, rotated with a certain angle.
Can you write Python code for it?

import numpy as np

x = np.arange(len(counts))
print(x)
plt.bar(x, votes);
plt.xticks(x, names, rotation=60);
plt.yticks(votes);


I am working on the file "Chapters-colab/Chapter_21_Tables_and_Networks.ipynb".
The first task is:
1. Tables
There are (at least) two ways to output your data as a formatted table:

Using the tabulate package. (You might need to install it first, using conda install tabulate)
Using the pandas dataframe method df.to_latex(...), df.to_string(...), or even df.to_clipboard(...).

This is extremely useful if you're writing a paper. First version of the 'results' section: done!
Option 1: Tabulate
Can you write Python code for it?

from tabulate import tabulate

table = [["spam",42],["eggs",451],["bacon",0]]
headers = ["item", "qty"]

# Documentation: https://pypi.python.org/pypi/tabulate
print(tabulate(table, headers, tablefmt="latex_booktabs"))


I am working on the file "Chapters-colab/Chapter_21_Tables_and_Networks.ipynb".
The first task is:
Now we can actually start drawing the graph. We'll increase the figure size, and use the draw_spring method (that implements the Fruchterman-Reingold layout algorithm).
Can you write Python code for it?

# Increasing figure size for better display of the graph.
from pylab import rcParams
rcParams['figure.figsize'] = 11, 11

# Draw the actual graph.
nx.draw_spring(G,with_labels=True)


I am working on the file "Chapters-colab/Chapter_21_Tables_and_Networks.ipynb".
The first task is:
Once you've produced your LaTeX table, it's almost ready to put in your paper. If you're writing an NLP paper and your table contains scores for different system outputs, you might want to make the best scores bold, so that they stand out from the other numbers in the table.
More to explore
The pandas library is really useful if you work with a lot of data (we'll also use it below). As Jake Vanderplas said in the State of the tools video, the pandas DataFrame is becoming the central format in the Python ecosystem. Here is a page with pandas tutorials.
2. Networks
Some data is best visualized as a network. There are several options out there for doing this. The easiest is to use the NetworkX library and either plot the network using Matplotlib, or export it to JSON or GEXF (Graph EXchange Format) and visualize the network using external tools.
Let's explore a bit of WordNet today. For this, we'll want to import the NetworkX library, as well as the WordNet module. We'll look at the first synset for dog: dog.n.01, and how it's positioned in the WordNet taxonomy. All credits for this idea go to this blog.
Can you write Python code for it?

import networkx as nx # You might need to install networkx first (conda install -c anaconda networkx)
from nltk.corpus import wordnet as wn
from nltk.util import bigrams # This is a useful function.


I am working on the file "Chapters-colab/Chapter_22_Sentiment_analysis_with_VADER.ipynb".
The first task is:
2. Load VADER model
The model can be loaded in the following way.
Can you write Python code for it?

from nltk.sentiment.vader import SentimentIntensityAnalyzer

vader_model = SentimentIntensityAnalyzer()


I am working on the file "Chapters-colab/Chapter_22_Sentiment_analysis_with_VADER.ipynb".
The first task is:
Chapter 22 - Sentiment analysis using VADER
In this notebook, we focus on sentiment analysis, which is the task of determining whether a text expresses a negative, neutral, or positive opinion. We introduce how to work with VADER as part of the NLTK to perform sentiment analysis. Given a sentence, e.g., "I like Python", VADER will predict a sentiment score on a scale from -1 to 1. The goal of this notebook is to show you how to work with VADER. One of the learning goals of the accompanying assignment is to gain insight into VADER by reading blogs about the system.
at the end of this notebook, you will:

have VADER installed on your computer
be able to load the VADER model
be able to apply the VADER model on new sentences:
with and without lemmatization
with providing VADER with certain parts of speech, e.g., providing the adjectives from a sentence as input to VADER

If you want to learn more about this chapter, you might find the following links useful:

blog on sentiment analysis
GitHub repository
this blog

If you have questions about this chapter, please contact us (cltl.python.course@gmail.com).
1. Downloading VADER package
Please run the following commands to download VADER to your computer.
Can you write Python code for it?

import nltk

# You only need to run this cell once.
# After that, you can comment it out.

nltk.download('vader_lexicon', quiet=False)


I am working on the file "Chapters-colab/Chapter_22_Sentiment_analysis_with_VADER.ipynb".
The first task is:
Perhaps you are surprised to see that there is no difference in the output! This is useful information for you to try to understand how the system works! Perhaps there are sentences for which it does matter. Feel free to experiment with other sentences.
3.2 Filter on part of speech
You can also filter on the part of speech, i.e., we let VADER make a prediction by only considering the nouns, verbs, or adjectives. The manipulation of the input to VADER allows you to gain insight how the system works.
Only Nouns:
Can you write Python code for it?

run_vader(nlp,
          sentences[1],
          lemmatize=True,
          parts_of_speech_to_consider={'NOUN'},
          verbose=1)


I am working on the file "Chapters-colab/Chapter_22_Sentiment_analysis_with_VADER.ipynb".
The first task is:
Please note that in this case, VADER only considers day to predict the sentiment score and ignores all other words. Do you agree with the assessment that day is neutral? I hope you have a great day!
Only verbs:
Can you write Python code for it?

run_vader(nlp,
          sentences[1],
          lemmatize=True,
          parts_of_speech_to_consider={'VERB'},
          verbose=1)


I am working on the file "Chapters-colab/Chapter_22_Sentiment_analysis_with_VADER.ipynb".
The first task is:
The next for loop assigns a sentiment score from VADER to each sentence.
Can you write Python code for it?

for sent in sentences:
    scores = vader_model.polarity_scores(sent)
    print()
    print('INPUT SENTENCE', sent)
    print('VADER OUTPUT', scores)


I am working on the file "Chapters-colab/Chapter_22_Sentiment_analysis_with_VADER.ipynb".
The first task is:
The next function defines an API to process texts (textual_unit) using different settings. This function operates on texts and assumes spaCy is loaded with the corresponding language model as we just did. Take a little time to analyze the function, which uses certain spaCy token properties to process the text in different ways and returns the VADER sentiment.
Can you write Python code for it?

def run_vader(nlp,
              textual_unit,
              lemmatize=False,
              parts_of_speech_to_consider=set(),
              verbose=0):
    """
    Run VADER on a sentence from spacy

    :param nlp: spaCy model
    :param str textual unit: a textual unit, e.g., sentence, sentences (one string)
    (by looping over doc.sents)
    :param bool lemmatize: If True, provide lemmas to VADER instead of words
    :param set parts_of_speech_to_consider:
    -empty set -> all parts of speech are provided
    -non-empty set: only these parts of speech are considered
    :param int verbose: if set to 1, information is printed
    about input and output

    :rtype: dict
    :return: vader output dict
    """
    doc = nlp(textual_unit)

    input_to_vader = []

    for sent in doc.sents:
        for token in sent:

            if verbose >= 2:
                print(token, token.pos_)

            to_add = token.text

            if lemmatize:
                to_add = token.lemma_

                if to_add == '-PRON-':
                    to_add = token.text

            if parts_of_speech_to_consider:
                if token.pos_ in parts_of_speech_to_consider:
                    input_to_vader.append(to_add)
            else:
                input_to_vader.append(to_add)

    scores = vader_model.polarity_scores(' '.join(input_to_vader))

    if verbose >= 1:
        print()
        print('INPUT SENTENCE', sent)
        print('INPUT TO VADER', input_to_vader)
        print('VADER OUTPUT', scores)

    return scores


I am working on the file "Chapters-colab/Chapter_22_Sentiment_analysis_with_VADER.ipynb".
The first task is:
To verify that the download was successful, you can run the following command.
Can you write Python code for it?


I am working on the file "Chapters-colab/Chapter_22_Sentiment_analysis_with_VADER.ipynb".
The first task is:
VADER provides a dictionary containing four ratings, i.e., keys, for each sentence.
The sentence is rated on how negative (key neg), positive (key pos), and neutral (key neu), it is.
Also, there is a compound key that combines the values of the keys neg, pos, and neu into one single score, i.e., the compound key. The compound value ranges from -1, i.e., very negative, to 1, i.e., very positive. You can read more about the VADER system on this blog.
3. Using spaCy to manipulate the input to VADER
In the examples in Section 2, VADER always takes into account each token, i.e., word, in the sentence to arrive at its sentiment prediction. In this section,
we are going to use spaCy to manipulate the input to VADER. This is one way to gain insight into how language systems work, i.e., by manipulating the input and inspecting the output.
We use spaCy as a tool to manipulate the input to VADER.
Please first install spaCy by following the instructions from Chapter 19 - More about Natural Language Processing Tools (spaCy) -- Section 2.1 Installing and loading spaCy
Can you write Python code for it?

import spacy
nlp = spacy.load('en') # en_core_web_sm


I am working on the file "Chapters/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/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/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/Chapter 01 - Getting Started with Variables and Values.ipynb".
The first task is:
2.2 Variable names
Note that the variable names text and x used above are not part of Python. In principle, you could use any name you like. Even if you change the variable text to something silly like pikachu or sniffles, the example would still work:
Can you write Python code for it?

sniffles = "Hello, world!"
print(sniffles)


I am working on the file "Chapters/Chapter 01 - Getting Started with Variables and Values.ipynb".
The first task is:
2.3 Copying/referencing variables
We can also 'copy' the contents of a variable into another variable, which is what happens in the code below. In fact, what is happening is that the variable second_number now refers to the same data object as first_number. You should of course watch out in such cases: make sure that you keep track of the value of each individual variable in your code (later in the course, we will see that this is especially tricky with data types that are mutable (i.e. things you can modify after you created them), such as lists).
Can you write Python code for it?

first_number = 5
print(first_number)
second_number = first_number
first_number = 3
print(first_number)
print(second_number)


I am working on the file "Chapters/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/Chapter 01 - Getting Started with Variables and Values.ipynb".
The first task is:
Exercise 5:
Write a program that asks two people for their names using input(). Store the names in variables called name1 and name2. Say hello to both of them.
Can you write Python code for it?

# adapt the code
name1 = "Paul"
print("Hello,", name1)


I am working on the file "Chapters/Chapter 01 - Getting Started with Variables and Values.ipynb".
The first task is:
Exercise 6:
The following piece of code will not work. You can see this, because it will print an error message (more on this in the following chapters). Can you figure out how to fix it?
Hint 1: Look at the quite (') characters.
Hint 2: You can use single quotes (') and double quites(") to define strings.
Can you write Python code for it?

my_text = 'The word 'python' has many meanings in natural language. '


I am working on the file "Chapters/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/Chapter 01 - Getting Started with Variables and Values.ipynb".
The first task is:
We can also assign numerical values to variables:
Can you write Python code for it?


I am working on the file "Chapters/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/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/Chapter 02 - Basic Data Types (Integers and Floats).ipynb".
The first task is:
2.1 Mathematical operators
There are several mathematical operators, some of which we have already seen above:
| Operation | Result |
|-----------|--------|
| x + y | sum of x and y|
| x - y | difference of x and y   |
| x * y | product of x and y       |
| x / y | quotient of x and y          |
| x // y |    floored quotient of x and y  |
| x % y | remainder of x / y  |
| -x |    x negated        |
| +x |    x unchanged       |
| x ** y |    x to the power y |
You will undoubtedly remember from your math classes in high school that there is something called operator precedence, meaning that multiplication, for instance, will always be executed before subtraction. In Python you can explicitly set the order in which arithmetic operations are executed, using round brackets. Compare the following lines of code:
Can you write Python code for it?


I am working on the file "Chapters/Chapter 02 - Basic Data Types (Integers and Floats).ipynb".
The first task is:
2.2 A common shortcut: +=
Suppose that we buy a new book for the office today: we can now update our book count accordingly, by adding one to our previous count:
Can you write Python code for it?

number_of_books = number_of_books + 1
print(number_of_books)


I am working on the file "Chapters/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/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/Chapter 02 - Basic Data Types (Integers and Floats).ipynb".
The first task is:
Exercise 3:
Please print the type of the following variables:
Can you write Python code for it?

var1 = 365
var2 = 3.14
var3 = "hi there"


I am working on the file "Chapters/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/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/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/Chapter 02 - Basic Data Types (Integers and Floats).ipynb".
The first task is:
Other types of conversions are possible as well, but of course not all conversions make sense. For example, we cannot make an integer of the string "hello":
Can you write Python code for it?


I am working on the file "Chapters/Chapter 02 - Basic Data Types (Integers and Floats).ipynb".
The first task is:
Similarly, we can convert an integer into a string using str(), after which it can be concatenated with another string:
Can you write Python code for it?

x = 2
y = " apples"
z = str(x) + y
print(z)
print(type(z))


I am working on the file "Chapters/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/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/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/Chapter 03 - Strings.ipynb".
The first task is:
1.1 Multi-line strings
Strings in Python can also span across multiple lines, which can be useful for when you have a very long string, or  when you want to format the output of the string in a certain way. This can be achieved in two ways:

With single or double quotes, where we manually indicate that the rest of the string continues on the next line with a backslash.
With three single or double quotes.

We will first demonstrate how this would work when you use one double or single quote.
Can you write Python code for it?

# This example also works with single-quotes.
long_string = "A very long string\n\
can be split into multiple\n\
sentences by appending a newline symbol\n\
to the end of the line."

print(long_string)


I am working on the file "Chapters/Chapter 03 - Strings.ipynb".
The first task is:
1.2 Internal representation: using repr()
As we have seen above, it is possible to make strings that span multiple lines. Here are two ways to do so:
Can you write Python code for it?

multiline_text_1 = """This is a multiline text, so it is enclosed by triple quotes.
Pretty cool stuff!
I always wanted to type more than one line, so today is my lucky day!"""
multiline_text_2 = "This is a multiline text, so it is enclosed by triple quotes.\nPretty cool stuff!\nI always wanted to type more than one line, so today is my lucky day!"
print(multiline_text_1)
print() # this just prints an empty line
print(multiline_text_2)


I am working on the file "Chapters/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/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/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/Chapter 03 - Strings.ipynb".
The first task is:
5. Printing, concatenating and inserting strings
You will often find yourself concatenating and printing combinations of strings. Consider the following examples:
Can you write Python code for it?

print("Hello", "World")
print("Hello " + "World")


I am working on the file "Chapters/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/Chapter 03 - Strings.ipynb".
The first task is:
Another hidden character that is often used is \t, which represents tabs:
Can you write Python code for it?

colors = "yellow\tgreen\tblue\tred"
print(colors)
print(repr(colors))


I am working on the file "Chapters/Chapter 03 - Strings.ipynb".
The first task is:
Another way of comparing strings is to check whether a string is part of another string, which can be done using the in operator. It returns True if the string contains the relevant substring, and False if it doesn't. These two values (True and False) are called boolean values, or booleans for short. We'll talk about them in more detail later. Here are some examples to try (can you predict what will happen before running them?):
Can you write Python code for it?

"fun" in "function"

"I" in "Team"

"am" in "Team"

"App" in "apple" # Capitals are not the same as lowercase characters!

"apple" in "apple"

"applepie" in "apple"


I am working on the file "Chapters/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/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/Chapter 03 - Strings.ipynb".
The first task is:
Can you exchange the first and last characters in my_string ('aananb')? Create a new variable new_string to store your result.
Can you write Python code for it?

my_string = "banana"
new_string = # your code here


I am working on the file "Chapters/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/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/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/Chapter 03 - Strings.ipynb".
The first task is:
Even though they may look similar, there are two different things happening here. Simply said: the plus in the expression is doing concatenation, but the comma is not doing concatenation.
The 'print()' function, which we have seen many times now, will print as strings everything in a comma-separated sequence of expressions to your screen, and it will separate the results with single blanks by default. Note that you can mix types: anything that is not already a string is automatically converted to its string representation.
Can you write Python code for it?

number = 5
print("I have", number, "apples")


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

the letter 'd' in my_string
the letter 'c' in my_string
Can you write Python code for it?

my_string = "Sandwiches are yummy"
# your code here


I am working on the file "Chapters/Chapter 03 - Strings.ipynb".
The first task is:
Exercise 4:
Find a way to fix the spacing problem below keeping the "+".
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/Chapter 03 - Strings.ipynb".
The first task is:
Exercise 5:
Replace all a's by o's in 'banana' using a string method.
Can you write Python code for it?


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


I am working on the file "Chapters/Chapter 03 - Strings.ipynb".
The first task is:
If you'd like to know what one of these methods does, you can just use help() (or look it up online):
Can you write Python code for it?


I am working on the file "Chapters/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/Chapter 03 - Strings.ipynb".
The first task is:
In the example above the error indicates that there is something wrong with the letter s. This is because the single quote closes the string we started, and anything after that is unexpected.
To solve this we can enclose the string in double quotes, as follows:
Can you write Python code for it?

restaurant = "Wendy's"
# Similarly, we can enclose a string containing double quotes with single quotes:
quotes = 'Using "double" quotes enclosed by a single quote.'


I am working on the file "Chapters/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/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/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/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/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/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/Chapter 03 - Strings.ipynb".
The first task is:
This is called string slicing. So how does this notation work?
python
my_string[i]                  # Get the character at index i.
my_string[start:end]          # Get the substring starting at 'start' and ending *before* 'end'.
my_string[start:end:stepsize] # Get all characters starting from 'start', ending before 'end',
                              # with a specific step size.
You can also leave parts out:
python
my_string[:i]                 # Get the substring starting at index 0 and ending just before i.
my_string[i:]                 # Get the substring starting at i and running all the way to the end.
my_string[::i]                # Get a string going from start to end with step size i.
You can also have negative step size. my_string[::-1] is the idiomatic way to reverse a string.

Tip: Slicing and accessing values via indices is very useful and can be applied to other python objects, which have a fixed sequence, such as lists (we will see how in the subsequent notebooks). Try to understand what is going on with string slicing - it will be very helpful in rest of the course!
Do you know what the following statements will print?
Can you write Python code for it?

print(my_string[1:4])

print(my_string[1:4:1])

print(my_string[11:14])

print(my_string[15:])

print(my_string[:9])

print('cow'[::2])

print('cow'[::-2])

# a fun trick to reverse sequences:
print(my_string[::-1])

# You can do something similar with lists (you don't have to understand this is detail now - but we'll show you an
# example already, so you've seen it):

my_list = ['a', 'bunch', 'of', 'words']
print(my_list[3])
print(my_list[2:4])
print(my_list[-1])


I am working on the file "Chapters/Chapter 03 - Strings.ipynb".
The first task is:
We can even do cool stuff like this with f-strings:
Can you write Python code for it?

text = f"Soon, I'm turning {age+1} years."
print(text)


I am working on the file "Chapters/Chapter 03 - Strings.ipynb".
The first task is:
What do the methods lstrip() and rstrip() do? Try them out below.
Can you write Python code for it?

# find out what lstrip() and rstrip() do


I am working on the file "Chapters/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/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/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/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/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/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/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/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/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/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/Chapter 04 - Boolean Expressions and Conditions.ipynb".
The first task is:
Not really, right? Luckily, Python has another trick to deal with this type of examples: [all and any]((https://docs.python.org/3/library/functions.html#all). Given a list of boolean expressions, this is how they work:
| operation | function |
|-----------|--------|
| all | True if all boolean expressions are True, otherwise False |
| any | True if at least one boolean expression is True, otherwise False |
If you don't completely understand all() and any(), don't worry, you will not necessarily need them right now. They are just a nice alternative to make your code more readable and you may appreciate that in the future.
Here are some examples of all():
Can you write Python code for it?

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

list_bools1 = ['a' in letters,
                2 in numbers]
print(list_bools1)
boolean_expression1 = all(list_bools1)
print(boolean_expression1)

list_bools2 = ['a' in letters,
                20 in numbers]
print(list_bools2)
boolean_expression2 = all(list_bools2)
print(boolean_expression2)


I am working on the file "Chapters/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/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/Chapter 04 - Boolean Expressions and Conditions.ipynb".
The first task is:
Remember:
- if-if: your code wil check all the if statements
- if-elif: if one condition results to True, it will not check the other conditions
Unless you need to check all conditions, using if-elif is usually preferred because it's more efficient.
3. Indentation
Let's take another look at the example from above (we've added line numbers):
python
1. if number <= 5:
2.     print(number)
3. else:
4.     print('number is higher than 5')
You might have noticed that line 2 starts with 4 spaces. This is on purpose! The indentation lets Python know when it needs to execute the piece of code. When the boolean expression in line 1 is True, Python executes the code from the next line that starts four spaces or one tab (an indent) to the right. This is called indentation. All statements with the same distance to the right belong to the same 'block' of code.
Unlike other languages, Python does not make use of curly braces to mark the start and end of pieces of code, like if statements. The only delimiter is a colon (:) and the indentation of the code. Both four spaces and tabs can be used for indentation. This indentation must be used consistently throughout your code. The most popular way to indent is four spaces (see stackoverflow). For now, you do not have to worry about this, since a tab is automatically converted to four spaces in notebooks.
Take a look at the code below. We see that the indented block is not executed, but the unindented lines of code are. Now go ahead and change the value of the person variable. The conversation should be a bit longer now!
Can you write Python code for it?

person = "John"
print("hello!")
if person == "Alice":
    print("how are you today?")                  #this is indented
    print("do you want to join me for lunch?")   #this is indented
elif person == "Lisa":
    print("let's talk some other time!")         #this is indented
print("goodbye!")


I am working on the file "Chapters/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")


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


I am working on the file "Chapters/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/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/Chapter 05 - Core concepts of containers.ipynb".
The first task is:
And that is correct! Of course, we can specify a value for the keyword parameters. We provide the a space ' ' for sep and 2 for maxsplit.
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(' ', 2)
print(words)


I am working on the file "Chapters/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/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/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/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/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/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/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/Chapter 06 - Lists.ipynb".
The first task is:
2.  How to add items to a list
The most common way of adding an item to a list is by using the append method.
Let's first look at the help message of this method to understand it better:
Can you write Python code for it?


I am working on the file "Chapters/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/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/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/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/Chapter 06 - Lists.ipynb".
The first task is:
Exercises
Exercise 1:
Create an empty list and add three names (strings) to it using the append method
Can you write Python code for it?


I am working on the file "Chapters/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/Chapter 06 - Lists.ipynb".
The first task is:
Obviously, we can also use negative indices:
Can you write Python code for it?

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


I am working on the file "Chapters/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/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/Chapter 06 - Lists.ipynb".
The first task is:
The count method has one positional parameter value and returns an integer. As the name already indicates, the method returns how often the value occurs in the list.
Can you write Python code for it?

friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']
number_of_bobs = friend_list.count('Bob')
print(number_of_bobs)

friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']
number_of_franks = friend_list.count('Frank')
print(number_of_franks)

help(list.index)


I am working on the file "Chapters/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/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/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/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/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/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/Chapter 07 - Sets.ipynb".
The first task is:
3. How to extract/inspect items in a set
When you use sets, you usually want to compare the elements of different sets, for instance, to determine how much overlap there is or how many of the items in set1 are not members of set2. Sets can be used to carry out mathematical set operations like union, intersection, difference, and symmetric difference. Please take a look at this website if you prefer a more visual and more complete explanation.
You can ask Python to show you all the set methods by using dir. All the methods that do not start with '__' are relevant for you.
Can you write Python code for it?


I am working on the file "Chapters/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/Chapter 07 - Sets.ipynb".
The first task is:
But the following example will result in an error, since we are trying to create a set with a mutable object
Can you write Python code for it?


I am working on the file "Chapters/Chapter 07 - Sets.ipynb".
The first task is:
Curly brackets surround sets, and commas separate the elements in the set
A set can be empty (use set() to create it)
Sets do not allow duplicates
sets are unordered (the order in which you add items is not important)
A set can only contain immutable objects (for now that means only strings and integers can be added)
A set can not contain mutable objects, hence no lists or sets

Please note that sets do not allow duplicates. In the example below, the integer 1 will only be present once in the set.
Can you write Python code for it?


I am working on the file "Chapters/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/Chapter 07 - Sets.ipynb".
The first task is:
Please note that sets are unordered. This means that it can occur that if you print a set, it looks different than how you created it
Can you write Python code for it?


I am working on the file "Chapters/Chapter 07 - Sets.ipynb".
The first task is:
Please note that sets can only contain immutable objects. Hence the following examples will work, since we are adding immutable objects
Can you write Python code for it?


I am working on the file "Chapters/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/Chapter 08 - Comparison of lists and sets.ipynb".
The first task is:
1.2 Order (with respect to how elements are added to it)

list: yes
set: no

The order in which you add elements to a list matters. Please look at the following example:
Can you write Python code for it?

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


I am working on the file "Chapters/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/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/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/Chapter 08 - Comparison of lists and sets.ipynb".
The first task is:
This does not
Can you write Python code for it?


I am working on the file "Chapters/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/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/Chapter 09 - Looping over containers.ipynb".
The first task is:
4. Tuples
One data structure (a new one!) is very frequently used with for loops. This data structure is a tuple. It's very simple to create a tuple.
Can you write Python code for it?


I am working on the file "Chapters/Chapter 09 - Looping over containers.ipynb".
The first task is:
5.1 Using tuples in a for-loop
In addition, tuples are often used with for-loops. When working with Python, it's quite common that you end up with data structures like the following example:
Can you write Python code for it?

language_data = [('the', 'determiner'),
                 ('house', 'noun'),
                 ('is', 'verb'),
                 ('big', 'adjective')]


I am working on the file "Chapters/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/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/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/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/Chapter 09 - Looping over containers.ipynb".
The first task is:
Exercise 4:
You could even do this with a set. However, not a good idea either? Why? Hint: Think about order.
Can you write Python code for it?

a_set = {1,2,3,}
first_el, second_el, third_el = a_set
print(first_el)
print(second_el)
print(third_el)


I am working on the file "Chapters/Chapter 09 - Looping over containers.ipynb".
The first task is:
In the two examples above, not all letters in the word 'hippopotamus' are printed. Both break and continue teleport you to another part of the code. break teleports out of the loop, continue teleports you to the next iteration of the loop.
Exercises
Exercise 1:
Use a loop to print each word in the list in a new line (i.e. only use a single print statement and do not use '\n' to start a new line).
Can you write Python code for it?

sentence = 'Now I know a lot about looping'
word_list = sentence.split()

# your code here


I am working on the file "Chapters/Chapter 09 - Looping over containers.ipynb".
The first task is:
Note about unpacking
Unpacking is an operation that can also be used with other containers, for instance, with lists:
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)


I am working on the file "Chapters/Chapter 09 - Looping over containers.ipynb".
The first task is:
Usually, you would like to loop through such an example. One way of doing that is the following:
Can you write Python code for it?

for item in language_data:
    print(item[0], item[1])


I am working on the file "Chapters/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/Chapter 10 - Dictionaries.ipynb".
The first task is:
2. How to create a dictionary
Let's take another look at the student_grades dictionary.
Can you write Python code for it?

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


I am working on the file "Chapters/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/Chapter 10 - Dictionaries.ipynb".
The first task is:
Exercise 2:
Print the number of pineapples you would like to buy by using only one line of code and without printing the entire dictionary.
Can you write Python code for it?


I am working on the file "Chapters/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/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/Chapter 10 - Dictionaries.ipynb".
The first task is:
However, what if we want to know which students got a 8 or higher? The items method is very useful for this scenario. Please carefully look at the following code snippet.
Can you write Python code for it?

student_grades = {'Frank': 8, 'Susan': 7, 'Guido': 10}
print(student_grades.items())


I am working on the file "Chapters/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/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/Chapter 10 - Dictionaries.ipynb".
The first task is:
In order to avoid getting an error, you can use an if-statement
Can you write Python code for it?

key = 'Piet'
if key in student_grades:
    print(student_grades[key])
else:
    print(key, 'not in dictionary')

key = 'Frank'
if key in student_grades:
    print(student_grades[key])
else:
    print(key, 'not in dictionary')


I am working on the file "Chapters/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/Chapter 10 - Dictionaries.ipynb".
The first task is:
Please note that the value is in fact a dictionary:
Can you write Python code for it?


I am working on the file "Chapters/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/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/Chapter 10 - Dictionaries.ipynb".
The first task is:
Python actually has a module, which is very useful for counting. It's called collections.
Can you write Python code for it?

from collections import Counter

word_freq = Counter(['Obama', 'was', 'the', 'president', 'of', 'the', 'USA'])
print(word_freq)


I am working on the file "Chapters/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/Chapter 10 - Dictionaries.ipynb".
The first task is:
You can do this as well with lists
Can you write Python code for it?

a_sentence = ['Obama', 'was', 'the', 'president', 'of', 'the', 'USA']
word2freq = dict()

for word in a_sentence:

    if word in word2freq: # add 1 to the dictionary if the keys exists
        word2freq[word] += 1
    else:
        word2freq[word] = 1 # set default value to 1 if key does not exists

    print(word, word2freq)

print()
print(word2freq)


I am working on the file "Chapters/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/Chapter 11 - Functions and scope.ipynb".
The first task is:
1.4.2 Positional vs keyword parameters and arguments
The function definition tells Python which parameters are positional and which are keyword. As you might remember, positional means that you have to give an argument for that parameter;  keyword means that you can give an argument value, but this is not necessary because there is a default value.
So, to summarize these two notes, we distinguish between:
1) positional parameters: (we indicate these when defining a function, and they are compulsory when calling the function)
2) keyword parameters: (we indicate these when defining a function, but they have a default value - and are optional when calling the function)
For example, if we want to have a function that can either multiply two or three numbers, we can make the third parameter a keyword parameter with a default of 1 (remember that any number multiplied with 1 results in that number):
Can you write Python code for it?

def multiply(x, y, third_number=1): # x and y are positional parameters, third_number is a keyword parameter
    """Multiply two or three numbers and print the result."""
    result=x*y*third_number
    print(result)

multiply(2,3) # We only specify values for the positional parameters
multiply(2,3,third_number=4) # We specify values for both the positional parameters, and the keyword parameter


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
1.5 Output: the return statement
Functions can have a return statement. The return statement returns a value back to the caller and always ends the execution of the function. This also allows us to use the result of a function outside of that function by assigning it to a variable:
Can you write Python code for it?

def multiply(x, y):
    """Multiply two numbers and return the result."""
    multiplied = x * y
    return multiplied

#here we assign the returned value to variable z
result = multiply(2, 5)

print(result)


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
1.6 Documenting your functions with docstrings
Docstring is a string that occurs as the first statement in a function definition.
For consistency, always use """triple double quotes""" around docstrings. Triple quotes are used even though the string fits on one line. This makes it easy to expand it later.
There's no blank line either before or after the docstring.
The docstring is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g., don't write "Returns the pathname ...".
In practice, there are several formats for writing docstrings, and all of them contain more information than the single sentence description we mention here. Probably the most well-known format is reStructured Text. Here is an example of a function description in reStructured Text (reST):
Can you write Python code for it?

def my_function(param1, param2):
    """
    This is a reST style.

    :param param1: this is a first param
    :param param2: this is a second param
    :returns: this is a description of what is returned
    """
    return


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
2. Variable scope
Please note: scope is a hard concept to grasp, but we think it is important to introduce it here. We will do our best to repeat it during the course.
Any variables you declare in a function, as well as the arguments that are passed to a function will only exist within the scope of that function, i.e., inside the function itself. The following code will produce an error, because the variable x does not exist outside of the function:
Can you write Python code for it?

def setx():
    """Set the value of a variable to 1."""
    x = 1

setx()
print(x)


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
Also consider this:
Can you write Python code for it?

x = 0
def setx():
    """Set the value of a variable to 1."""
    x = 1
setx()
print(x)


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
Even when we return x, it does not exist outside of the function:
Can you write Python code for it?

def setx():
    """Set the value of a variable to 1."""
    x = 1
    return x

setx()
print(x)


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
Exercise 2:
Add another keyword parameter message to the multiply function, which will allow a user to print a message. The default value of this keyword parameter should be an empty string. Test this with 2 messages of your choice. Also test it without specifying a value for the keyword argument when calling a function.
Can you write Python code for it?

# function to modify:

def multiply(x, y, third_number=1):
    """Multiply two or three numbers and print the result."""
    result=x*y*third_number
    print(result)


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
Exercise 3:
Write a function called multiple_new_lines which takes as argument an integer and prints that many newlines by calling the function newLine.
Can you write Python code for it?

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

# you code here


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
Exercise 4:
Let's refactor the happy birthday function to have no repetition. Note that previously we print "Happy birthday to you!" three times. Make another function happy_birthday_to_you() that only prints this line and call it inside the function happy_birthday(name).
Can you write Python code for it?

def happy_birthday_to_you():
    # your code here

# original function - replace the print statements by the happy_birthday_to_you() function:
def happy_birthday(name):
    """
    Print a birthday song with the "name" of the person inserted.
    """
    print("Happy Birthday to you!")
    print("Happy Birthday to you!")
    print("Happy Birthday, dear " + name + ".")
    print("Happy Birthday to you!")


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
Exercise 6:
Complete this code to switch the values of two variables:
Can you write Python code for it?

def switch_two_values(x,y):
# your code here

a='orange'
b='apple'

a,b = switch_two_values(a,b) # `a` should contain "apple" after this call, and `b` should contain "orange"

print(a,b)


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
Functions can have multiple parameters. We can for example multiply two numbers in a function (using the two parameters x and y) and then call the function by giving it two arguments:
Can you write Python code for it?

def multiply(x, y):
    """Multiply two numeric values."""
    result = x * y
    print(result)

multiply(2020,5278238)
multiply(2,3)


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
However, when the actual output is different from what we expected, we got an error. Let's say we made a mistake in writing the function.
Can you write Python code for it?

def is_even(p):
    """Check whether a number is even."""
    if p % 2 == 1:
        return False
    else:
        return False

input_value = 2
expected_output = True
actual_output = is_even(input_value)
assert actual_output == expected_output, f'expected {expected_output}, got {actual_output}'


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
If the function output is what you expect, Python will show nothing.
Can you write Python code for it?

input_value = 2
expected_output = True
actual_output = is_even(input_value)
assert actual_output == expected_output, f'expected {expected_output}, got {actual_output}'


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
If we assign the result to a variable, but do not use the return statement, the function cannot return it. Instead, it returns None (as you can try out below).
This is important to realize: even functions without a return statement do return a value, albeit a rather boring one. This value is called None (it’s a built-in name). You have seen this already with list methods - for example list.append(val) adds a value to a list, but does not return anything explicitly.
Can you write Python code for it?

def multiply_no_return(x, y):
    """Multiply two numbers and does not return the result."""
    result = x * y

is_this_a_result = multiply_no_return(2,3)
print(is_this_a_result)


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
If we execute the code above, we don't get any output. That's because we only told Python: "Here's a function to do this, please remember it." If we actually want Python to execute everything inside this function, we have to call it:
1.3 How to call a function
It is important to distinguish between a function definition and a function call. We illustrate this in 1.3.1. You can also call functions from within other functions. This will become useful when you split up your code into small chunks that can be combined to solve a larger problem. This is illustrated in 1.3.2.
1.3.1) A simple function call
A function is defined once. After the definition, Python has remembered what this function does in its memory.
A function is executed/called as many times as we like. When calling a function, you should always use parenthesis.
Can you write Python code for it?

# function definition:

def happy_birthday_to_emily(): # Function definition
    """
    Print a birthday song to Emily.
    """
    print("Happy Birthday to you!")
    print("Happy Birthday to you!")
    print("Happy Birthday, dear Emily.")
    print("Happy Birthday to you!")

# function call:

print('Function call 1')

happy_birthday_to_emily()

print()
# We can call the function as many times as we want (but we define it only once)
print('Function call 2')

happy_birthday_to_emily()

print()

print('Function call 3')

happy_birthday_to_emily()

print()
# This will not call the function

print('This is not a function call')
happy_birthday_to_emily


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
In fact, this code has produced two completely unrelated x's!
So, you can not read a local variable outside of the local context. Nevertheless, it is possible to read a global variable from within a function, in a strictly read-only fashion.
Can you write Python code for it?

x = 1
def getx():
    """Print the value of a variable x."""
    print(x)

getx()


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
Make sure you actually save your 2 values into 2 variables, or else you end up with errors or unexpected behavior:
Can you write Python code for it?

#this will assign `var` to a tuple:
var = calculate(10,5)
print(var)

#this will generate an error
var1, var2, var3 = calculate(10,5)


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
Returning multiple values
Similarly as the input, a function can also return multiple values as output. We call such a collection of values a tuple (does this term sound familiar ;-)?).
Can you write Python code for it?

def calculate(x,y):
    """Calculate product and sum of two numbers."""
    product = x * y
    summed = x + y

    #we return a tuple of values
    return product, summed

# the function returned a tuple and we unpack it to var1 and var2
var1, var2 = calculate(10,5)

print("product:",var1,"sum:",var2)


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
The help we get on a function will become more interesting once we learn about function inputs and outputs ;-)
1.4 Working with function input
1.4.1 Parameters and arguments
We use parameters and arguments to make a function execute a task depending on the input we provide. For instance, we can change the function above to input the name of a person and print a birthday song using this name. This results in a more generic function.
To understand how we use parameters and arguments, keep in mind the distinction between function definition and function call.
Parameter: The variable name in the function definition below is a parameter. Variables used in function definitions are called parameters.
Argument: The variable my_name in the function call below is a value for the parameter name at the time when the function is called. We refer to such variables as arguments. We use arguments so we can direct the function to do different kinds of work when we call it at different times.
Can you write Python code for it?

# function definition with using the parameter `name'
def happy_birthday(name):
    """
    Print a birthday song with the "name" of the person inserted.
    """
    print("Happy Birthday to you!")
    print("Happy Birthday to you!")
    print(f"Happy Birthday, dear {name}.")
    print("Happy Birthday to you!")

# function call using specifying the value of the argument
happy_birthday("James")


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
We can also print the result directly (without assigning it to a variable), which gives us the same effect as using the print statements we used before:
Can you write Python code for it?


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
We can also store the name in a variable:
Can you write Python code for it?


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
You can do the same tricks that we learnt to apply on the built-in functions, like asking for help or for a function type:
Can you write Python code for it?


I am working on the file "Chapters/Chapter 11 - Functions and scope.ipynb".
The first task is:
You can use two built-in functions in Python when you are unsure whether a variable is local or global. The function locals() returns a list of all local variables, and the function globals() - a list of all global variables. Note that there are many non-interesting system variables that these functions return, so in practice it is best to check for membership with the in operator. For example:
Can you write Python code for it?

a=3
b=2

def setb():
    """Set the value of a variable b to 11."""
    b=11
    c=20
    print("Is 'a' defined locally in the function:", 'a' in locals())
    print("Is 'b' defined locally in the function:", 'b' in locals())
    print("Is 'b' defined globally:", 'b' in globals())

setb()

print("Is 'a' defined globally:", 'a' in globals())
print("Is 'b' defined globally:", 'b' in globals())

print("Is 'c' defined globally:", 'c' in globals())