"- run cell below to save the figure as an svg\n",
"- open the figure to check that it works (view in VS Code or in your web browser)\n",
"- add Markdown to your README then visualize to confirm you did it properly (remember to use `CTRL+SHIFT+V` in VSC, the [Markdown All-in-one extension](https://mude.citg.tudelft.nl/2024/book/external/learn-programming/book/install/ide/vsc/extensions.html#markdown-all-in-one))\n",
"- make a commit to your repo that includes the change to the README as well as the file itself"
"- add Markdown to your `myfigure.md`-file then visualize to confirm you did it properly (remember to use `CTRL+SHIFT+V` in VSC, the [Markdown All-in-one extension](https://mude.citg.tudelft.nl/2024/book/external/learn-programming/book/install/ide/vsc/extensions.html#markdown-all-in-one))\n",
"- make a commit to your repo that includes the change to the `myfigure.md`-file as well as the file itself"
*[CEGM1000 MUDE](http://mude.citg.tudelft.nl/): Week 1.5. Due: before Friday, Oct 4, 2024.*
%% Cell type:markdown id:f5a4caf7 tags:
The purpose of this notebook is to introduce a few useful Python and Markdown topics:
1. assert statements
2. list comprehension
3. plt.bar()
4. including a figure in a Markdown document
**Remember that there is a survey that must be completed to pass this PA.**
[Here is a link to the survey](https://forms.office.com/e/saRwPUyL8d).
%% Cell type:markdown id:a0330b70 tags:
## Topic 1: Assert Statements
Assert statements are like small little "fact-checkers" that you can insert into your code to make sure it is doing what you think it should do. For example, if a matrix should be 4x6 you can use an assert statement to check this; if the matrix is not the right size, and error will occur. Although your first thought may be "why would I want to make my code break with an error?!?!" it turns out this is a very useful debugging and testing tool (something we will cover in a later PA as well). The reason it is useful is that it causes your code to break for a _very specific_ reason, so that you can identify problems and fix them efficiently and confidently. Sounds useful, right?! Luckily assert statements are also quite simple:
There are two cases of this statement that we will use:
Case 1:
```
assert <logical_argument>
```
Case 2:
```
assert <logical_argument>, 'my error message'
```
The best way to illustrate the use of this tool is by example. But first, some important information about the `<logical_argument>`.
### Background Information: Logical Statements
Another key aspect for using this tool effectively is to be aware of what a **logical statement** is and how they can be specified in Python.
A **logical statement** is simply a statement that can be evaluated as **true or false**. This is sometimes referred to as a **binary**, or, in computing in particular, a **Boolean**. Here are some examples of logical statements, formulated as questions, that have a binary/Boolean results:
- Is it raining?
- Is my computer on?
- Were you in class yesterday?
Here are some examples of questions that cannot be evaluated as a logical statement:
- How long will it rain for?
- When will my computer battery reach 0%?
- How many lectures have you skipped this week?
Each of these examples
Python expression that checks whether or not something is
Now try fixing the cell below by 1) adding your own error message (see Case 2 above), and 2) forcing the assert statement to fail. Confirm that you can see error message in the error report.
Explore assert statements by writing your own. Experiment with different data types (e.g., strings, floats, arrays, lists) and use different logical statements from the list above.
</p>
</div>
%% Cell type:code id:27fa2738 tags:
``` python
YOUR_CODE_HERE
```
%% Cell type:markdown id:56a7f3a3 tags:
### Summary of Asserts
You are now an expert on `assert` statements. Remember these key points:
- an assert statement answers a true/false question; it will will cause an error if false and do nothing if true
- the syntax is `assert <logical_statement>`
- you can easily customize the error message with the syntax `assert <logical_argument>, 'my error message'`
- the `<logical_statement>` must be a Boolean result
%% Cell type:markdown id:db9ff6b8 tags:
## Part 2: List Comprehension
List and dictionary *comprehensions* are elegant constructs in Python that allow you to manipulate Python objects in a very compact and efficient way. You can think of them as writing a `for` loop in a single line. Here is the syntax:
```
[<DO_SOMETHING> for <ITEM> in <ITERABLE>]
```
Note the following key elements:
- the list comprehension is enclosed in list brackets: `[ ... ]`
-`<DO_SOMETHING>` is any Python expression (for example, `print()` or `x**2`)
-`<ITEM>` is generally a (temporary) variable that is used in the expression `<DO_SOMETHING>` and represents all of the "items" in `<ITERABLE>`
-`<ITERABLE>` is an _iterable_ object. Don't worry about what this is, exactly (we will study it more later).
For our purposes, it is enough to consider the following _iterables_:
- lists (e.g., `[1, 2, 3]`)
- ndarrays (Numpy)
-`range()`
- dictionaries
As with assert statements, the best way to illustrate this is by example.
Now try it yourself! Create a new list from from the one defined below that has values that are half that of the original.
<em>Note the use of asserts to make sure your answer is correct!</em>
</p>
</div>
%% Cell type:code id:1ca75689 tags:
``` python
my_list=[1,2,3,4,5]
new_list=[]
print(new_list)
assertnew_list==[0.5,1.0,1.5,2.0,2.5],"new_list values are not half of my_list!"
```
%% Cell type:markdown id:3e8b83e6 tags:
### Summary
There are several reasons why you should use list comprehension, hopefully you can recognize them from the examples and tasks above:
- Readability: Comprehensions often turn multiple lines of code into a single, readable line, making the code easier to understand at a glance.
- Efficiency: They are generally faster because they are optimized in the Python interpreter.
- Simplicity: Reduces the need for loop control variables and indexing, making the code simpler.
Sometimes the hardest thing to remember is the order and syntax. The following list comprehension uses obvious variable names to illustrate it (assuming you have an object with "stuff" in it, for example, `objects = [1, 2, 3]`); if you can remember this, you can remember list comprehensions!
```
[print(object) for object in objects]
```
%% Cell type:markdown id:16632cc2 tags:
## The `plt.bar()` Method
At this point we have created many figures in MUDE assignments using a method from the Matplotlib plotting library: `plt.plot()`. This is our "bread and butter" plot because it is so easy to plot lines, data, scatter plots, etc. However, there are _many_ more types of plots available in Matplotlib. Today we will try `bar()`, which, as you can imagine, creates bar plots.
First take a look at the documentation and see if you can figure out how it works.
That's right, it plots a bar chart where the first argument is the x coordinate of the bar and the second argument is the height. Fill in the empty lists below to create a bar plot with any values you like.
</p>
</div>
%% Cell type:code id:512718a3 tags:
``` python
plt.bar([],[])
```
%% Cell type:markdown id:82b94893 tags:
Pretty easy, right? Let's try to do one more thing with this - suppose we don't like that the _center_ of the bar is over the value we enter. It's easy to change this using a _keyword argument_; these are the input arguments to the function that have the equals sign (e.g., `function(keyword_arg=<xxx>)`). These are optional arguments; they are generally not needed, but can be specified, along with a value, to change the default behavior of the function. For our purposes this week, we will want to change _two_ keyword arguments:
1.`width`
2.`align`
Fortunately the `help` function printed out the docstring for `bar()`, which contains all the information you need to figure out what these keyword arguments do and how to use them.
Set the keyword arguments below to make the bars fill up the entire space between each bar (no white space) and to force the <b>left</b> side of the bar to align with the value specified.
Note the addition of keyword argument <code>edgecolor</code> to make it easier to see the edges of the bar.
Now set the keyword arguments below to make the bars fill up the entire space between each bar (no white space) and to force the <b>right</b> side of the bar to align with the value specified.
</p>
</div>
%% Cell type:code id:4958e71a tags:
``` python
plt.bar([1,2,3,4],[0.2,0.5,0.1,0.6],
width=YOUR_CODE_HERE,
align=YOUR_CODE_HERE,
edgecolor='black')
```
%% Cell type:markdown id:58811f81 tags:
## Topic 4: Exporting a Figure and Including it in a Markdown Notebook
Now that we can create a wider variety of figures, we should be able to include them in our Reports for communicating the results of our analyses. Here we show you a very simple way to save a figure generated in your notebook, then use Markdown to visualize the figure. Once a figure is made it is easy, use this syntax:
```

```
The label is simply a name that will appear in case the figure fails to load. It can also be read by a website-reading app (for example, then a blind person could understand what the content of the figure may be). Here is an example for what this could look like in practice:
```

```
This is very easy, so once again we lead by example! However, first a couple notes about filepaths.
### File Paths
A _file path_ is like an address to a file. There are generally two types, _absolute_ and _relative._ Most of our activities focus on working in a _working directory,_ so we will focus almost entirely on relative paths. The general format is like this:
```
./subdirectory_1/subdir_2/filename.ext
```
where:
- the dot `.` indicates one should use the current directory of the file (or the CLI) as the current location (the `.` is like saying " start _here_")
- forward slashes `/` separate subdirectories
- the last two words are the file name and extension. For example, common image extensions are `.jpg`, `.png` or `.svg`
- in this example, the image file is stored inside a folder called `subdir_2` which is inside a folder called `subdirectory_1` which is in our working directory.
As a general rule, **always use forward slashes whenever possible.** Although backward slashes are the default and must be used at times on Windows, they don't work on Mac or Linux systems. This causes problems when sharing code with others running these systems (or when we check your assignments on GitHub!!!). Remember that we try to do things in a way that allows easy collaboration: using approaches that are agnostic of the operating system (i.e., works on all platforms). This is hard to guarantee in practice, but consistently using forward slashes will get us close!
### Try it out yourself
We will try this out, but first we need to create a figure! The code below is a quick way of saving a Matplotlib figure as an svg file.
Task:
- run cell below to save the figure as an svg
- open the figure to check that it works (view in VS Code or in your web browser)
- add Markdown to your README then visualize to confirm you did it properly (remember to use `CTRL+SHIFT+V` in VSC, the [Markdown All-in-one extension](https://mude.citg.tudelft.nl/2024/book/external/learn-programming/book/install/ide/vsc/extensions.html#markdown-all-in-one))
- make a commit to your repo that includes the change to the README as well as the file itself
- add Markdown to your `myfigure.md`-file then visualize to confirm you did it properly (remember to use `CTRL+SHIFT+V` in VSC, the [Markdown All-in-one extension](https://mude.citg.tudelft.nl/2024/book/external/learn-programming/book/install/ide/vsc/extensions.html#markdown-all-in-one))
- make a commit to your repo that includes the change to the `myfigure.md`-file as well as the file itself
Test your understanding of relative file paths by moving the csv file to a subdirectory with name <code>test</code> and getting the following Markdown cell to display the figure.
<pre>
<code>

</code>
</pre>
</p>
</div>
%% Cell type:markdown id:b23f5743 tags:
** MAKE SURE A FIGURE APPEARS HERE BY MOVING THE FILE**