Merge branch 'master'

pull/10/head
Tim Skov Jacobsen 2019-12-03 10:08:20 +01:00
commit 0fcb6d8a00
4 changed files with 1254 additions and 1426 deletions

View File

@ -1,12 +1,15 @@
# Try Python without installation
If you want to try out the basics without installing Python on your PC, try the online interpreter in this link:
> https://www.onlinegdb.com/online_python_interpreter
> <a href="https://www.pythonanywhere.com/try-ipython/" target="_blank">https://www.pythonanywhere.com/try-ipython/</a>
Make sure to select Python 3 as language in the top right of the site.
You'll be able to follow along with the first three sessions by this approach. Starting from Session 4 a dedicated Python installation and an editor is needed.
# Installation guide for Python environment
***Nov. 2019***
> ***Note:***
>_This guide does not nesessarily always refer to the latest released version._
@ -14,65 +17,79 @@ You'll be able to follow along with the first three sessions by this approach. S
>_Also, there do exist alternative ways of installing Python. While, the section below describes the recommended method also presumed in the crash course, the most popular alternative are also described below._
## Recommended installation
This is the installation approach we recommend. Please skim through it before starting.
### 1. Download and install the basic Python application
A direct link to the installation executeable for Python 3.7.5 (64-bit) are given below.
A direct link to the installation executeable for Python 3.7.5 (64-bit) are given below.
On python.org you can find a more recent 3.8.0 release, but we do not yet recommend installing that.
> https://www.python.org/ftp/python/3.7.5/python-3.7.5-amd64.exe
> <a href="https://www.python.org/ftp/python/3.7.5/python-3.7.5-amd64.exe" target="_blank">https://www.python.org/ftp/python/3.7.5/python-3.7.5-amd64.exe</a>
Avoid installing it for all users, as this will require admin rights (also whenever installing 3rd-party packages in the future).
![](Python_all_users.png)
![alt text](Python_all_users.png)
**Remember** to select the "Add Python to environment variables". In this way you don't have to navigate to the installation folder everytime you want to use Python.
![](Python_path.png)
![alt text](Python_path.png)
### 2. Download and install Git (if you intend to use version control)
A direct link to the installation executeable for the latest Git 2.24.0 (64-bit) is given below (the official git homepage is git-scm.com).
> https://github.com/git-for-windows/git/releases/download/v2.24.0.windows.1/Git-2.24.0-64-bit.exe
> <a href="https://github.com/git-for-windows/git/releases/download/v2.24.0.windows.1/Git-2.24.0-64-bit.exe" target="_blank">https://github.com/git-for-windows/git/releases/download/v2.24.0.windows.1/Git-2.24.0-64-bit.exe</a>
### 3. Download and install a code editor
An code editor is the software interface supporting you in writing your code. This could in principle be Notepad, but much more advanced editors suited for programming exist with syntax highlighting, auto completion and much more. Note that you're free to change editor at any time.
We recommend that you start with **Visual Studio Code (VS Code)**, the now most popular free code editor in the world. A direct link to the installation executeable is provided below.
> https://aka.ms/win32-x64-user-stable
> <a href="https://aka.ms/win32-x64-user-stable" target="_blank">https://aka.ms/win32-x64-user-stable</a>
To set up Visual Studio Code properly to run Python scripts, follow this guide from Step 2: [VS Code Python setup](#Visual-Studio-Code---Installation).
> **Note:** For users who come from Matlab and want a similar editor experience, another editor called Spyder might be a good choice. If you want to go this route, follow the alternative installation below, as Spyder works best with that approach.
## Alternative installation - Miniconda
Miniconda is a lightwieght version of a common distribution of Python called Anaconda, it's supposed to be a more user friendly installation. This installation makes it easy to work in an editor called Spyder, which has a lot of similarities with the Matlab environment.
### 1. Download and install Miniconda
Choose the installer file with Python 3.7 that suits your Windows system from this site:
>https://docs.conda.io/en/latest/miniconda.html
> <a href="https://docs.conda.io/en/latest/miniconda.html" target="_blank">https://docs.conda.io/en/latest/miniconda.html</a>
In the installation section called *Advanced Installation Options*, check the box saying _Add Anaconda to my PATH environment variable_. It will say that it's not recommended, but do it anyway.
![](Add_anaconda_to_path.png)
![alt text](Add_anaconda_to_path.png)
Other than this, just choose defaults for the installation.
### 2. Install Anaconda Navigator
Go to Windows Start, type `anaconda prompt` and open the program. Don't get scared by the DOS-look.
In the program, type
```
conda install -c anaconda anaconda-navigator
```
and press enter to install. Type `y` when it asks.
![](Anaconda_prompt.png)
![alt text](Anaconda_prompt.png)
### 3. Install editor
An editor is the software where the actual code is written. This could in principle be Notepad, but much more advanced editors suited for programming exist. These have syntax highlighting, auto completion while typing and much more.
Shipped with the Anaconda Navigator comes an easy way to install two editors:
### Visual Studio Code (VS Code)
***Recommended editor for people taking the 201 course***
* Many features and customization options
@ -83,6 +100,7 @@ Shipped with the Anaconda Navigator comes an easy way to install two editors:
This is the editor KEKL and TSJA will be using.
### Spyder
***Recommended editor for people who wants a Matlab-like environment***
* Easier to understand for beginners, especially when coming from Matlab
@ -92,48 +110,57 @@ This is the editor KEKL and TSJA will be using.
> **Note:** If you don't like one editor you can always install the other later.
### Visual Studio Code - Installation
1. **Install Visual Studio Code from Anaconda Naviagtor.**
If it's already installed the button will say "launch" instead of "install".
2. **Setup editor for running code**
* Launch the editor and go the the _Extensions_ tab on the left panel (short key: <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>X</kbd>)
* Make sure that the extension called Python is installed, which it should be already (Note that this editor that support all programming languages, not just Python)
* Make sure that the extension called Python is installed, which it should be already (Note that this editor support many programming languages, not just Python)
* Search for and install the extension called _Code Runner_.
3. **Select the Python version to connect to VS Code**
* This might seem unnecessary, but some people have many versions of Python installed on their system.
* Go to _View_ -> _Command Palette_. Write `Python: Select Interpreter` and choose the interpreter (there should only be one at this point):
* In case nothing shows up when you search "Python: Select Interpreter", try reinstalling the Python extension.
4. **Create a Python file and run it**
* Go to _File_ -> _New file_. In the file write: `print('Hello world!')`. Save it and choose Python as file type in the dropdown.
* After saving you should see the syntax highlighting take effect.
* Press <kbd>CTRL</kbd>+<kbd>ALT</kbd>+<kbd>N</kbd> to run the script. The output in the bottom of the screen should now say `'Hello world!'`
> **Note:** If you get the error `'python' is not recognized as an internal or external command`, try restarting the editor. Sometimes it requires a restart for the interpreter setting to take effect.
* Press <kbd>CTRL</kbd>+<kbd>ALT</kbd>+<kbd>N</kbd> or press the _play_ icon on the upper right to run the script. The output in the bottom of the screen should now say `'Hello world!'`
> **Note:** If you get the error `'python' is not recognized as an internal or external command`, try restarting the editor. Sometimes it requires a restart for the interpreter setting to take effect.
Everything should now be ready!
After using it for a while, you might get annoyed by having to save the file before each run of the script. If you want to save it automatically before running, do this:
Go to the gear icon in the bottom left -> Settings -> Text Editor and scroll down to Edit in settings.json. Open the link and add this line in between the curly brackets:
Go to the gear icon in the bottom left -> Settings -> Text Editor and scroll down to _Edit in settings.json_ (or search for it). Open the link and add this line in between the curly brackets:
```python
"code-runner.saveFileBeforeRun": true,
```
#### Code Linter
A code linter highlights code not aligned with best practice formatting.
To activate linter:
* Press <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>P</kbd>
* Search for _select linter_
* Chose _pycodestyle_ (follows the PEP8 guideline)
VS Code will promt you with any missing pip packages. Just accept these for automatic installation.
### Spyder - Installation
1. **Install Spyder from Anaconda Naviagtor.**
If it's already installed the button will say "launch" instead of "install".
2. **Create a Python file and run it**
Spyder will already have a `temp.py` file created. Write `print('Hello world!)` and use the green arrow to run the code.
Spyder will already have a `temp.py` file created. Write `print('Hello world!)` and use the green arrow to run the code.
You can also create your own file as `some_name.py` and run the command in that.

View File

@ -1,6 +1,7 @@
![](https://www.python.org/static/community_logos/python-logo-master-v3-TM.png)
# Python 101 - Python for Beginners
![python.org logo](https://www.python.org/static/community_logos/python-logo-master-v3-TM.png)
## Python 101 - Python for Beginners
[![License](https://img.shields.io/github/license/Python-Crash-Course/Python101)](https://github.com/Python-Crash-Course/Python101/blob/master/LICENSE)
[![GitHub stars](https://img.shields.io/github/stars/Python-Crash-Course/Python101)](https://github.com/Python-Crash-Course/Python101/stargazers)
[![Issues Open](https://img.shields.io/github/issues-raw/Python-Crash-Course/Python101)](https://github.com/Python-Crash-Course/Python101/issues)
@ -9,14 +10,17 @@
[![Last Commit](https://img.shields.io/github/last-commit/Python-Crash-Course/Python101)](https://github.com/Python-Crash-Course/Python101/commits/master)
[![Contributors](https://img.shields.io/github/contributors/Python-Crash-Course/Python101)](https://github.com/orgs/Python-Crash-Course/people)
This GitHub repository contains material for a beginner Python course held in COWI Lyngby during 2019/2020.
## Sessions Notes and Exercises
This GitHub repository contains material for a beginner Python course held in COWI Lyngby during 2019/2020. Check out its [GitHub page](https://python-crash-course.github.io/Python101/).
If you don't have Python installed please check out the [Python environment installation guideline](https://python-crash-course.github.io/Python101/Installation/installation_guide.html).
## Sessions Notes and Exercises
Descriptions and exercises for each session are in the format of Jupyter Notebooks. The links below provide convenient ways to view the notebooks for each session.
In the *code* tab of this repository there will be a folder for each session. In case an exercise requires additional files like csv files or scripts, they will be present there.
* [Session 0 - Introduction](https://nbviewer.jupyter.org/github/Python-Crash-Course/Python101/blob/master/Session%200%20-%20Introduction/Session%200%20-%20Exercises.ipynb)
* [Session 0 - Warm-up exercises](https://nbviewer.jupyter.org/github/Python-Crash-Course/Python101/blob/master/Session%200%20-%20Introduction/Session%200%20-%20Exercises.ipynb) (Download introduction PowerPoint [here](https://github.com/Python-Crash-Course/Python101/raw/master/Session%200%20-%20Introduction/Session%200%20-%20Introduction.pptx))
* [Session 1 - Data Types](https://nbviewer.jupyter.org/github/Python-Crash-Course/Python101/blob/master/Session%201%20-%20Data%20Types/Session%201%20-%20Data%20Types.ipynb)
@ -36,7 +40,6 @@ In the *code* tab of this repository there will be a folder for each session. In
* [Session 9 - Heatmaps and Merging Operation](https://nbviewer.jupyter.org/github/Python-Crash-Course/Python101/blob/master/Session%209%20-%20Heatmaps%20and%20merging%20operation/Session%209%20-%20Heatmaps%20and%20merging%20operations.ipynb)
## Session Exercise Solutions
* Session 0 - Introduction (No solutions)
@ -59,33 +62,33 @@ In the *code* tab of this repository there will be a folder for each session. In
* [Session 9 - Heatmaps and Merging Operations](https://nbviewer.jupyter.org/github/Python-Crash-Course/Python101/blob/master/Session%209%20-%20Heatmaps%20and%20merging%20operation/Session%209%20-%20Exercise%20Solutions.ipynb)
## Course Notes
Some notes have been prepared for the course, but is still work in progress:
[Course Notes (work in progress)](https://nbviewer.jupyter.org/github/Python-Crash-Course/Python101/blob/master/Course%20Notes/Python%20Course%20Notes.ipynb)
These notes have some content that overlaps with the notes for each session, but is in general a more overall description. It also contains more detailed explanations of some topics that did not fit into the session notes.
These notes have some content that overlaps with the notes for each session, but is in general a more overall description. It also contains more detailed explanations of some topics that did not fit into the session notes.
## Useful Links
### General
* [PEP8 (Style guide for Python code)](https://www.python.org/dev/peps/pep-0008/)
* [Online interpretor (write code without installing an editor)](https://www.onlinegdb.com/online_python_interpreter#)
### Beginner Tutorials
* [Interactive Tutorial from DataCamp](https://www.datacamp.com/courses/intro-to-python-for-data-science)
* [Interactive Tutorial from DataCamp](https://www.datacamp.com/courses/intro-to-python-for-data-science)
### Videos
* [Corey Schafer](https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g)
- Videos with very clear and beginner friendly explanations of programming. Most of the videos focus on Python. Go to playlists and find the beginner tutorials to get started.
* Videos with very clear and beginner friendly explanations of programming. Most of the videos focus on Python. Go to playlists and find the beginner tutorials to get started.
* [Sentdex](https://www.youtube.com/user/sentdex)
- Videos on many topics ranging from beginner to advanced.
* Videos on many topics ranging from beginner to advanced.
### Git and GitHub
* [What is GitHub?](https://www.youtube.com/watch?v=w3jLJU7DT5E) - Good video explanation from the GitHub Youtube Channel
@ -98,13 +101,12 @@ These notes have some content that overlaps with the notes for each session, but
* [Git and GitHub for Beginners](https://readwrite.com/2013/09/30/understanding-github-a-journey-for-beginners-part-1/)
### Coding Challenge Sites
* [CodeWars (Coding challenge site)](https://www.codewars.com/)
* [Edabit (Coding challenge site)](https://edabit.com/)
* [Edabit (Coding challenge site)](https://edabit.com/)
### Miscellaneous
* [Python Data Science Handbook](https://jakevdp.github.io/PythonDataScienceHandbook/)
@ -116,6 +118,3 @@ These notes have some content that overlaps with the notes for each session, but
* [Pactical Business Python (Pandas focused website)](https://pbpython.com/)
* [Common Excel Tasks Demonstrated in Pandas](https://pbpython.com/excel-pandas-comp.html)

File diff suppressed because it is too large Load Diff

View File

@ -9,13 +9,12 @@
"\n",
"Data structures are constructs that can contain one or more variables. They are containers that can store a lot of data into a single entity.\n",
"\n",
"**Python's four basic data structures are**\n",
"**Python's four basic data structures are:**\n",
" * Lists\n",
" * Dictionaries\n",
" * Tuples\n",
" * Sets\n",
"\n",
" \n",
"## Lists \n",
"Lists are defined by square brackets `[]` with elements separated by commas. They can have elements of any data type.\n",
"\n",
@ -24,7 +23,6 @@
"### List syntax \n",
"<code> L = [item_1, item_2, ..., item_n] </code>\n",
"\n",
"\n",
"### Mutability\n",
"Lists are ***mutable***. They can be changed after creation.\n",
"\n",
@ -53,13 +51,11 @@
"metadata": {},
"source": [
"## Dictionaries\n",
"Dictionaries have key/value pairs which are enclosed in curly brackets`{}`. A value can be fetched by querying the corresponding key. \n",
"This can for some problems be much easier than having two lists that relate to each other by index.\n",
"Dictionaries have key/value pairs which are enclosed in curly brackets`{}`. A value can be fetched by querying the corresponding key. Refering the data via logically named keys instead of list indexes makes the code more readable.\n",
"\n",
"### Dictionary syntax \n",
" \n",
"<code> d = {key1: value1, key2: value2, ..., key_n, value_n} </code>\n",
"\n",
"<code> d = {key1: value1, key2: value2, ..., key_n: value_n} </code>\n",
" \n",
"Note that values can be of any data type like floats, strings etc., but they can also be lists or other data structures.\n",
"\n",
@ -389,12 +385,12 @@
"## Indexing \n",
"When elements are put into a sequences (strings, lists, tuples etc.), the individual elements gets an index assgined to them. This enables each element to be extracted. \n",
" \n",
"> **Indexing in Python** starts from `0`, while the negative index starts from `-1`.\n",
"> **Indexing in Python starts from `0`**, while the last element can be access via index `-1`.\n",
"\n",
"![image.png](attachment:image.png)\n",
"\n",
"### Use square brackets `[]`\n",
"To extract an element by indexing, use sqaure brackets `[]`. This is the general way and works for all sequences. Strings, lists and tuples are all sequences."
"### Use square brackets `[]` to access elements\n",
"To extract an element by indexing, use sqaure brackets `[]`. This is the general way and works for all sequences."
]
},
{
@ -437,7 +433,7 @@
}
],
"source": [
"# Extract second to last element\n",
"# Extract second last element\n",
"example_list[-2]"
]
},
@ -505,7 +501,7 @@
"metadata": {},
"source": [
"### Extracting values from dictionaries\n",
"Dictionaries differ from data structures like strings, lists and tuples since **they do not have an index**. Instead, a value is extracted by indexing the corresponding key:"
"Dictionaries differ from data structures like strings, lists and tuples since **they do not have an index**. Instead, a value is extracted by using the corresponding key:"
]
},
{
@ -533,8 +529,6 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that this means that **keys in a dictionary must be unique!**\n",
"\n",
"See demonstation below, where the key `'a'` is defined twice. The second defintion overwrites the first one."
]
},
@ -573,10 +567,10 @@
"\n",
"> **When slicing**, the stop point of the slice is not included.\n",
"\n",
"Examples is this section are shown for lists, but the same concept works for strings and tuples. Set objects do not support indexing/slicing since they are unordered, and dictionaries cannot be sliced either as they have the key functionality instead.\n",
"Examples in this section are shown for lists, but the same concept works for strings and tuples. Set objects do not support indexing/slicing since they are unordered, and dictionaries cannot be sliced either as they have the key functionality instead.\n",
"\n",
"### Common slicing operations \n",
"Suppose a list `n` has been defined along with two integers `n` and `n`:\n",
"Suppose a list `n` has been defined along with two integers `start` and `stop`:\n",
"\n",
"\n",
"```python\n",
@ -601,8 +595,6 @@
"# Copy of the whole list (alternative: list.copy())\n",
"n[:] -> [3, 25, 83, 31, 14, 47, 1, 23, 57] \n",
"```\n",
"The same concept works for other sequence like strings and tuples.\n",
"\n",
"\n",
"As seen, the last one creates a copy. This can be useful when working with mutable objects. For example for copying a list to mutate the copy while keeping the original list unchanged.\n",
"\n",
@ -912,8 +904,8 @@
],
"source": [
"# Printing numbers from 0-5\n",
"for i in [0, 1, 2, 3, 4, 5]:\n",
" print(i)"
"for num in [0, 1, 2, 3, 4, 5]:\n",
" print(num))"
]
},
{
@ -953,9 +945,9 @@
}
],
"source": [
"# Printing numbers from 0-5\n",
"for i in range(6):\n",
" print(i**2)"
"# Printing square of numbers from 0-5\n",
"for num in range(6):\n",
" print(num**2)"
]
},
{
@ -967,17 +959,13 @@
},
{
"cell_type": "code",
"execution_count": 30,
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"superman\n",
"spiderman\n",
"green lantern\n"
]
"text": "superman\nspiderman\ngreen lantern\n"
}
],
"source": [
@ -990,7 +978,45 @@
},
{
"cell_type": "markdown",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Note how for-loops in Python can avoid dealing with indexes, while still supporting the alternative."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "superman\nspiderman\ngreen lantern\n"
}
],
"source": [
"# Using enumerate to also gain access to the running index\n",
"for i, string in enumerate(strings):\n",
" if len(strings[i]) > 7: # If the current string has more than seven characters \n",
" print(strings[i]) # Print it"
]
},
{
"cell_type": "markdown",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (<ipython-input-2-4d251609901f>, line 2)",
"output_type": "error",
"traceback": [
"\u001b[1;36m File \u001b[1;32m\"<ipython-input-2-4d251609901f>\"\u001b[1;36m, line \u001b[1;32m2\u001b[0m\n\u001b[1;33m A `while` loop is a loop that continues until some condition is no longer satisfied.\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"## `while` loops\n",
"A `while` loop is a loop that continues until some condition is no longer satisfied.\n",
@ -1038,7 +1064,7 @@
"counter = 1\n",
"while counter < 5: \n",
" print(f'The count is {counter}')\n",
" counter += 1 # Update counter (equivalent to: counter=counter+1)"
" counter += 1 # Update counter (equivalent to: counter=counter+1)"
]
},
{
@ -1050,19 +1076,48 @@
"\n",
" > **Remember:** All code inside a `while`-block must be indented!\n",
"\n",
"A `while`-loop can be good when the number of iterations are unknown beforehand. This could be when searching for a root of an equation (e.g finding the neutral axis of a reinforced concrete section).\n",
"A `while`-loop can be good when the number of iterations are unknown beforehand. This could be when searching for a root of an equation.\n",
"\n",
"When iterating, convergence is not always guaranteed. A common way of exiting the `while`-loop is to define a max number of iterations and then check in each loop whether this number has been reached. If it has, then the loop should `break`.\n",
"\n",
"A similar logic to `while`-loops could be done with by `for`-loops, but a `while`-loop is cleaner for some purposes and can help to clarify the intent of the code."
]
},
{
"cell_type": "markdown",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Both for and while loops can be affected by `continue` and/or `break`. `Continue` starts on the next interation while skipping the rest of the code block and `break` stops the whole loop. The example above is reproduced below using `break`. This can sometime yield more readable code."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "The count is 1\nThe count is 2\nThe count is 3\nThe count is 4\n"
}
],
"source": [
"counter = 1\n",
"while True: \n",
" print(f'The count is {counter}')\n",
" counter += 1 # Update counter (equivalent to: counter=counter+1)\n",
" if counter > 4:\n",
" break # break out of while loop"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## List comprehensions\n",
"List comprehensions are other ways of writing `for`-loops. They can be done in one line and are often cleaner and more readable for simple iteration.\n",
"List comprehensions are another way of writing `for`-loops in a single line of code. They're generally faster and can be used for more compact representation of simple interations yielding more readable code.\n",
"\n",
"### General form of list comprehensions\n",
"The general form of the simplest list comprehension is\n",
@ -1106,7 +1161,7 @@
"L1 = [12, 215, 31, 437, 51]\n",
"\n",
"# List comprehension to multiply each element of L1 by 2\n",
"L2 = [2*i for i in L1] \n",
"L2 = [2*elem for elem in L1] \n",
"L2"
]
},
@ -1141,52 +1196,53 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"To get a vectorized behavior like that we could have use `numpy`, which is a third party library for numerical compuations similar to Matlab. Later sessions will explore `numpy` further."
"To get a vectorized behavior like that we could have used `numpy`, which is a hugely popular third party library for numerical compuations similar to Matlab. Later sessions will explore `numpy` further."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### List comprehension with `if`-statement \n",
"The general form of a list comprehension with a conditional is\n",
"~~~~python\n",
" result_list = [expression for item in iterable if condition]\n",
"~~~~\n",
" * `iterable` is a sequence that can be iterated over, this could be a list, a string, a tuple etc. \n",
" * `condition` is a logical condition, e.g. `item > 3`, which returns a boolean (`True`/`False`). This can act as as filter.\n",
" * `result_list` is a new list containing `expression` for each `item` that fulfilled the `condition`\n"
"# Exercise 7\n",
"From the following list, create a new list containing only the elements that have exactly five characters. \n",
"~~~python\n",
"phonetic_alphabet = ['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot']\n",
"~~~"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"An example where a list is filtered:"
"# Exercise 8\n",
"Find the intersection of the two sets (elements that occur in both sets)\n",
"~~~python\n",
"s1 = {'HE170B', 'HE210B', 'HE190A', 'HE200A', 'HE210A', 'HE210A'}\n",
"\n",
"s2 = {'HE200A', 'HE210A', 'HE240A', 'HE200A', 'HE210B', 'HE340A'}\n",
"~~~"
]
},
{
"cell_type": "code",
"execution_count": 34,
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[4, 5]"
]
"text/plain": "[4, 5]"
},
"execution_count": 34,
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Define a list (iterable)\n",
"x = [1, 2, 3, 4, 5] \n",
"# Exercise 9\n",
"Create a variable `fy` and set it equal to 435.\n",
"\n",
"# Filter list with list comprehension by use of condition\n",
"result_list = [i for i in x if i > 3]\n",
"result_list = [x for x in x if x > 3]\n",
"result_list"
]
},
@ -1194,7 +1250,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"### List comprehension with `if`-statement\n",
"### List comprehension with `if`-`else`-statement\n",
" \n",
"~~~~python\n",
" result_list = [expression1 if condition else expression2 for item in iterable]\n",
@ -1204,29 +1260,30 @@
"\n",
"* `condition` is a logical condition, e.g. `item > 3`, which returns a boolean (`True`/`False`). This can act as as filter.\n",
"\n",
"* `result_list` is a new list containing elements where each `item` depends on `condition`. If it is `True`, `expression1` is put in. Else `expression2` is put in. \n",
"\n"
"~~~python\n",
"T1 = (-18, -27, 2, -21, -15, 5)\n",
"~~~"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The added `else` allows us to retain the elements for which `condition` returns `False`:"
"# End of exercises\n",
"\n",
"*The cell below is for setting the style of this document. It's not part of the exercises.*"
]
},
{
"cell_type": "code",
"execution_count": 35,
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[0, 0, 182, 0, 151, 174]"
]
"text/plain": "[None, None, 182, None, 151, 174]"
},
"execution_count": 35,
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
@ -1236,7 +1293,7 @@
"v = [3, 62, 182, 26, 151, 174]\n",
"\n",
"# Set all elements of v that are less than 100 equal to 0\n",
"w = [0 if i < 100 else i for i in v]\n",
"w = [None if x < 100 else x for x in v]\n",
"w"
]
},
@ -1387,300 +1444,6 @@
"T1 = (-18, -27, 2, -21, -15, 5)\n",
"~~~"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# End of exercises\n",
"\n",
"*The cell below is for setting the style of this document. It's not part of the exercises.*"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<style>\n",
"/* div#notebook {\n",
" font-size: 13pt;\n",
" line-height: 120%;\n",
" color: #303030;\n",
" -webkit-font-smoothing: antialiased !important;\n",
" padding-top: 25px !important;\n",
"} */\n",
"\n",
"\n",
"body,\n",
"div.body {\n",
" font-family: Roboto;\n",
" /* font-size: 16pt; */\n",
" color: #303030;\n",
" /* background-color: #d1b5b5; */\n",
" /* background: #8f4f4f; */\n",
" margin-right: 10px;\n",
" /* -webkit-font-smoothing: antialiased !important; */\n",
"}\n",
"\n",
"/* Code inside HTML/Markdown */\n",
"div.rendered_html code {\n",
" border-radius: 5px;\n",
"}\n",
"\n",
"/* Output area from code cells */\n",
"div.output_area pre {\n",
" /* font-size: 11pt !important; */\n",
" color: #303030;\n",
"}\n",
"\n",
"\n",
"\n",
"/* HEADING 1 styles */\n",
"h1 {\n",
" font-family: 'Roboto', 'Signika', sans-serif;\n",
" font-weight: ligher;\n",
" font-style: normal;\n",
" /* font-size: 20pt; */\n",
" width: 100%;\n",
" text-align: left;\n",
" color: #EE7631;\n",
" border-bottom: 1px solid rgba(238, 118, 49, 0.575);\n",
" padding-bottom: 6px;\n",
" /* font-variant: small-caps; */\n",
" }\n",
" \n",
" /* table {\n",
" margin: 5px;\n",
" width: 290px;\n",
" }\n",
" \n",
" th {\n",
" padding: 3px;\n",
" }\n",
" \n",
" td {\n",
" padding-left: 8px;\n",
" padding-right: 8px;\n",
" border: 1px solid #990000;\n",
" background-color: #ffffcc;\n",
" }\n",
"\n",
" #trHeader {\n",
" text-decoration: underline;\n",
" color: #990000;\n",
" }\n",
" \n",
" .centerCell {\n",
" text-align: center;\n",
" } */\n",
"\n",
"/* HEADING 2 styles */\n",
"h2 {\n",
" font-family: \"Roboto\";\n",
" text-align: left;\n",
" /* font-size: 12pt; */\n",
" color: #EE7631;\n",
" margin-bottom: 5px;\n",
" /* border-bottom: 1px solid lightgray; */\n",
" border-bottom: 0.8px solid rgba(238, 118, 49, 0.575);\n",
" padding-bottom: 6px\n",
" }\n",
" \n",
" /* table {\n",
" margin: 5px;\n",
" width: 290px;\n",
" }\n",
" \n",
" th {\n",
" padding: 3px;\n",
" }\n",
" \n",
" td {\n",
" padding-left: 8px;\n",
" padding-right: 8px;\n",
" border: 1px solid #990000;\n",
" background-color: #ffffcc;\n",
" }\n",
"\n",
" #trHeader {\n",
" text-decoration: underline;\n",
" color: #990000;\n",
" }\n",
" \n",
" .centerCell {\n",
" text-align: center;\n",
" } */\n",
"\n",
"h3 {\n",
" font-family: 'Roboto';\n",
" /* text-align: left; */\n",
" /* font-size: 12pt; */\n",
" /* color: #EE7631; */\n",
" /* margin-bottom: 5px; */\n",
" border-bottom: 0.5px solid #ededed;\n",
" padding-bottom: 6px\n",
" }\n",
"\n",
"\n",
"\n",
"p {\n",
" font-family: Roboto;\n",
" font-size: 16px;\n",
"}\n",
"\n",
"/* Lists with dots */\n",
"ul {\n",
" font-size: 16px;\n",
" line-height: 150%;\n",
"}\n",
"\n",
"/* Lists with numbers */\n",
"ol {\n",
" font-size: 16px;\n",
" line-height: 150%;\n",
"}\n",
"\n",
"/* Horizontal rules */\n",
"hr { \n",
" margin-top: 3px; \n",
" margin-bottom: 3px \n",
"}\n",
"\n",
"/* Links */\n",
"a {\n",
" color: #EE7631;\n",
"}\n",
"\n",
"\n",
"/* Change global font size (for code) */\n",
".CodeMirror {\n",
"font-size: 16px !important;\n",
"font-family: monospace;\n",
"}\n",
"\n",
"\n",
"/* Code cells in the notebook - NOTE: color is font-color */\n",
".cm-s-ipython.CodeMirror {\n",
" font-family: monospace, monospace;\n",
" /* font-size: 11pt; */\n",
" background: #ededed;\n",
" color: #303030; \n",
" border-radius: 2px;\n",
" /* margin-right: 10px; */\n",
" font-style: normal;\n",
" font-weight: normal;\n",
"}\n",
"\n",
"\n",
"/* Background of code cells */\n",
".cm-s-ipython.CodeMirror {\n",
" font-family: monospace, monospace;\n",
" /* font-size: 11pt; */\n",
" background: rgba(211, 211, 211, 0.123);\n",
" color: #303030;\n",
" border-radius: 2px;\n",
" font-style: normal;\n",
" font-weight: normal;\n",
"}\n",
"\n",
"\n",
"/* .CodeMirror-gutters {\n",
" border: none;\n",
" border-right: 1px solid #e0e1e3 !important;\n",
" background-color: #e0e1e3 !important;\n",
" background: #e0e1e3 !important;\n",
" border-radius: 0px;\n",
" white-space: nowrap;\n",
"} */\n",
"\n",
"\n",
"\n",
"/* Code syntax highlithig theme */\n",
".cm-s-ipython .CodeMirror-cursor {\n",
" border-left: 2px solid #ff711a !important;\n",
"}\n",
".cm-s-ipython span.cm-comment {\n",
" color: #8d8d8d;\n",
" font-style: italic; \n",
"}\n",
".cm-s-ipython span.cm-atom {\n",
" color: #055be0;\n",
"}\n",
".cm-s-ipython span.cm-number {\n",
" color: #ff8132;\n",
"}\n",
".cm-s-ipython span.cm-property {\n",
" color: #303030;\n",
"}\n",
".cm-s-ipython span.cm-attribute {\n",
" color: #303030;\n",
"}\n",
".cm-s-ipython span.cm-keyword {\n",
" color: #a045ddf3;\n",
" font-weight: normal;\n",
"}\n",
".cm-s-ipython span.cm-string {\n",
" color: #009e07;\n",
"}\n",
".cm-s-ipython span.cm-meta {\n",
" color: #aa22ff;\n",
"}\n",
".cm-s-ipython span.cm-operator {\n",
" color: #055be0;\n",
"}\n",
".cm-s-ipython span.cm-builtin {\n",
" color: #3f2ce7;\n",
"}\n",
".cm-s-ipython span.cm-variable {\n",
" color: #303030;\n",
"}\n",
".cm-s-ipython span.cm-variable-2 {\n",
" color: #de143d;\n",
"}\n",
".cm-s-ipython span.cm-variable-3 {\n",
" color: #aa22ff;\n",
"}\n",
".cm-s-ipython span.cm-def {\n",
" color: #e22978;\n",
" font-weight: normal;\n",
"}\n",
".cm-s-ipython span.cm-error {\n",
" background: rgba(191,11,55,.70);\n",
"}\n",
".cm-s-ipython span.cm-tag {\n",
" color: #e22978;\n",
"}\n",
".cm-s-ipython span.cm-link {\n",
" color: #ef5c00;\n",
"}\n",
".cm-s-ipython span.cm-storage {\n",
" color: #055be0;\n",
"}\n",
".cm-s-ipython span.cm-entity {\n",
" color: #e22978;\n",
"}\n",
".cm-s-ipython span.cm-quote {\n",
" color: #009e07;\n",
"}\n",
"</style>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from IPython.display import HTML\n",
"HTML('<style>{}</style>'.format(open('../css/cowi.css').read()))"
]
}
],
"metadata": {
@ -1700,7 +1463,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.4"
"version": "3.7.3"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
@ -1744,4 +1507,4 @@
},
"nbformat": 4,
"nbformat_minor": 2
}
}