Skip to content

Commit

Permalink
Add all course notebooks
Browse files Browse the repository at this point in the history
  • Loading branch information
JeltevanBoheemen committed Nov 17, 2021
1 parent f8a32a5 commit 45b1bbe
Show file tree
Hide file tree
Showing 16 changed files with 3,019 additions and 2 deletions.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
# programming-in-python
Materials for the CDH course 'Programming in Python'
# Programming in Python

The entry level course 'Programming in Python', by the [Utrecht Centre for Digital Humanities](https://cdh.uu.nl/) aims to teach the basics of the Python programming language. Special attention is given to best practises in coding, e.g.: writing clean code and documentation.

The course was first taught 15-16 November, 2021.

This repository contains all teaching materials, exercises, solutions and extra resources relevant to the course. Where possible, all files are provided as Python Notebooks.
1 change: 1 addition & 0 deletions exercises/2_exercise.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"Exercise 2.ipynb","provenance":[],"collapsed_sections":[],"authorship_tag":"ABX9TyP0DJevbsf+LA115QvuuYbc"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","metadata":{"id":"QXRFmxivqk3J"},"source":["# Exercise 2\n","\n","1. \n"," 1. Loop over `exercise_list`, and find the word `\"stressed\"`. Assign it to a new variable.\n"," 2. Reverse the word you found in 1.1, and print the reversed word."]},{"cell_type":"code","metadata":{"id":"loap3-NPqqGD"},"source":["exercise_list = [1, 12.9, \"stressed\", \"bar\", True]"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"3leg-2-oqsmU"},"source":["2. Make a list of numbers. Print the average. See what happens when you try to add strings to the list."]},{"cell_type":"code","metadata":{"id":"qfYQgZ6UtGYX"},"source":[""],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"yL3K8Yygte30"},"source":["3. For each of the following lists, check if the first and last values are the same. Print `\"yay\"` if so, `\"nay\"` if not. Try to first turn them into a lists of lists. Are there any results you did not expect?"]},{"cell_type":"code","metadata":{"id":"EZvk0hKluPNy"},"source":["list1 = [1, 2, 3, 5, 1]\n","list2 = [1, 2, 3, 5, \"1\"]\n","list3 = [1, 2, 3, 5, True]\n","list4 = [False, \"True\", \"False\", \"False\"]\n","list5 = [\"true\", False, \"True\"]"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"FMySjPAXx4v1"},"source":["4. *FizzBuzz* (advanced)\n","\n"," 1. Print all numbers from 1 to 100. The numbers are provided by the code below.\n"," 2. If a number is divisible by 3, print `\"Fizz\"` instead.\n"," 3. If a nummber is divisible by 5, print `\"Buzz\"` instead.\n"," 4. If a number is divisible by 3 AND divisible by 5, print only`\"FizzBuzz\"`, not \"Fizz\" or \"Buzz\".\n","\n","Hint: use the modulo operator: `number1 % number2`. Try to see if you can figure out what it does.\n","\n"]},{"cell_type":"code","metadata":{"id":"Z3CaG-uhyngV"},"source":["numbers = list(range(0, 101))\n","print(2 % 3)\n","print(3 % 3)\n"],"execution_count":null,"outputs":[]}]}
1 change: 1 addition & 0 deletions exercises/2_solutions.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"Exercise 2 - solutions.ipynb","provenance":[],"collapsed_sections":[]},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","metadata":{"id":"v1wakPAeqvhA"},"source":["# Exercise 2 - Solutions"]},{"cell_type":"markdown","metadata":{"id":"iPcFeOQjuxE4"},"source":["## 1"]},{"cell_type":"code","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"0ZaiO9o6q7VO","executionInfo":{"status":"ok","timestamp":1636915394327,"user_tz":-60,"elapsed":5,"user":{"displayName":"Jelte van Boheemen","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GheLnTZKvy8P4D-Jl7hmsBhPGYHfOa1IeSLeP-Ynw=s64","userId":"10826796817228738014"}},"outputId":"261578b6-8d55-42f7-943a-38a0c27f8cb7"},"source":["exercise_list = [1, 12.9, \"stressed\", \"bar\", True]\n","\n","for element in exercise_list:\n"," if element == \"stressed\":\n"," word = element\n","\n","reversed_word = \"\"\n","for letter in word:\n"," reversed_word = letter + reversed_word\n","print(word + \" in reverse is: \" + reversed_word)"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["stressed in reverse is: desserts\n"]}]},{"cell_type":"markdown","metadata":{"id":"KYfCrRt1rbbd"},"source":["## 2"]},{"cell_type":"code","metadata":{"id":"4_FAlJ5irdkI"},"source":["numbers = [1, 5, -12, 38987, 0, 24]\n","\n","total = 0\n","length = 0\n","for num in numbers:\n"," total = total + num\n"," length = length + 1\n","average = total/length\n","print(average)\n","\n","# Adding strings makes the program fail, you cannot add a string to a number!\n","\n","# Bonus: using builtin functions\n","total = sum(numbers)\n","length = len(numbers)\n","print(total/length)"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"Eu7Idfj7uyv1"},"source":["## 3"]},{"cell_type":"code","metadata":{"id":"XOKAZfR0uzoy"},"source":["list1 = [1, 2, 3, 5, 1]\n","list2 = [1, 2, 3, 5, \"1\"],\n","list3 = [1, 2, 3, 5, True]\n","list4 = [False, \"True\", \"False\", \"False\"]\n","list5 = [\"banana\", \"bananas\", \"Banana\"]\n","\n","master_list = [list1, list2, list3, list4, list5]\n","for sub_list in master_list:\n"," if sub_list[0] == sub_list[-1]:\n"," print(\"yay\")\n"," else:\n"," print(\"nay\")\n","\n","# You might not expect list 3 to be a \"yay\"\n","# However, in Python False and True are equal to 0 and 1\n","print(False == 0)\n","print(True == 1)\n","\n","# list5 is a nay, because strings are case sensitive\n","# if you want to compare them case-insensitive, first make then all lowercase\n","print(\"banana\".lower() == \"Banana\".lower())"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"nY1j9g2dyoqc"},"source":["## 4"]},{"cell_type":"code","metadata":{"id":"qC2qt-sPypwM"},"source":["# Many optimizations are possible!\n","numbers = list(range(0, 101))\n","\n","for num in numbers:\n"," if num % 3 == 0 and num % 5 == 0:\n"," print(\"FizzBuzz\")\n"," elif num % 3 == 0:\n"," print(\"Fizz\")\n"," elif num % 5 == 0:\n"," print(\"Buzz\")\n"," else:\n"," print(num)"],"execution_count":null,"outputs":[]}]}
76 changes: 76 additions & 0 deletions exercises/3_exercise.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Exercise3.ipynb",
"provenance": [],
"collapsed_sections": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "Fj68DvsUltDP"
},
"source": [
"# Exercise 3\n",
"\n",
"This is the third hands-on exercise of the 2021 CDH entry level Python course at Utrecht University.\n",
"\n",
"For this exercise, you may choose whether you use your own code from exercise 2, or the code below. The exercise consists of two parts:\n",
"\n",
"1. Refactor the code into functions, so that the logic is reusable and non-repetitive and the purpose of each line of code is clear.\n",
"2. Identify any hard-coded parameters and replace them by constants that you define at the top.\n",
"\n",
"If you finish the exercise quickly, you can try whether you can generalize your functions to make them more powerful. For bonus points!\n",
"\n",
"Good luck!"
]
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "--nCEHqYlmKw",
"outputId": "e1294fd0-7353-4205-e887-f21e6a82719b"
},
"source": [
"name = 'Python' # could be your own name\n",
"print('We have a: ' + name[0])\n",
"print('We have a: ' + name[1])\n",
"print('We have a: ' + name[2])\n",
"print('We have a: ' + name[3])\n",
"print('We have a: ' + name[4])\n",
"print('We have a: ' + name[5])\n",
"print('Go go ' + name.upper() + '!!!')"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"We have a: P\n",
"We have a: y\n",
"We have a: t\n",
"We have a: h\n",
"We have a: o\n",
"We have a: n\n",
"Go go PYTHON!!!\n"
]
}
]
}
]
}
120 changes: 120 additions & 0 deletions exercises/3_solutions.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Exercise3-answer.ipynb",
"provenance": [],
"collapsed_sections": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "Fj68DvsUltDP"
},
"source": [
"# Exercise 3\n",
"\n",
"This is the third hands-on exercise of the 2021 CDH entry level Python course at Utrecht University.\n",
"\n",
"For this exercise, you may choose whether you use your own code from exercise 2, or the code below. The exercise consists of two parts:\n",
"\n",
"1. Refactor the code into functions, so that the logic is reusable and non-repetitive and the purpose of each line of code is clear.\n",
"2. Identify any hard-coded parameters and replace them by constants that you define at the top.\n",
"\n",
"Good luck!"
]
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "--nCEHqYlmKw",
"outputId": "e1294fd0-7353-4205-e887-f21e6a82719b"
},
"source": [
"name = 'Python' # could be your own name\n",
"print('We have a: ' + name[0])\n",
"print('We have a: ' + name[1])\n",
"print('We have a: ' + name[2])\n",
"print('We have a: ' + name[3])\n",
"print('We have a: ' + name[4])\n",
"print('We have a: ' + name[5])\n",
"print('Go go ' + name.upper() + '!!!')"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"We have a: P\n",
"We have a: y\n",
"We have a: t\n",
"We have a: h\n",
"We have a: o\n",
"We have a: n\n",
"Go go PYTHON!!!\n"
]
}
]
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "sc8aY_ZrT-Gh",
"outputId": "4b53cf51-4124-495a-e498-2bdb97079f4e"
},
"source": [
"ANNOUNCE_START = 'We have a: '\n",
"YELL_START = 'Go go '\n",
"YELL_END = '!!!'\n",
"\n",
"def announce(letter):\n",
" return ANNOUNCE_START + letter\n",
"\n",
"def yell(name):\n",
" return YELL_START + name + YELL_END\n",
"\n",
"def cheerlead(name):\n",
" lines = []\n",
" for letter in name:\n",
" lines.append(announce(letter))\n",
" lines.append(yell(name))\n",
" return '\\n'.join(lines)\n",
"\n",
"print(cheerlead('Python'))"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"We have a: P\n",
"We have a: y\n",
"We have a: t\n",
"We have a: h\n",
"We have a: o\n",
"We have a: n\n",
"Go go Python!!!\n"
]
}
]
}
]
}
69 changes: 69 additions & 0 deletions exercises/4_exercise.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Exercise4.ipynb",
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "bVfoqS2eXjOV"
},
"source": [
"# Exercise 4\n",
"\n",
"This is the fourth hands-on exercise of the 2021 CDH entry level Python course at Utrecht University.\n",
"\n",
"The following program takes in a binary string of ones and zeros. It returns `True` if all bits are ones and `False` otherwise. However, there is a bug in the program. In the example below, the program returns `True` while there is clearly a zero in the string.\n",
"\n",
"1. Insert a breakpoint and step through the program to find out what is going wrong. Step multiple times through the program if necessary and do not stop until you fully understand what is going on.\n",
"2. Try to think of at least two ways in which you might solve the problem. Which is the safest way to be *very* sure that the problem will *never* happen again?\n",
"\n",
"If you have written a program with a bug during exercise 2 or 3, you may choose to use that program for this exercise instead."
]
},
{
"cell_type": "code",
"metadata": {
"id": "3N0mSvSyXWe4",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "f0c90396-c2e0-45ed-d502-73b8e59f16e4"
},
"source": [
"def only_ones(binary_string):\n",
" for bit in binary_string:\n",
" if bit is '0':\n",
" return False\n",
" return True\n",
"\n",
"only_ones('1O1')"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 1
}
]
}
]
}
85 changes: 85 additions & 0 deletions exercises/4_solutions.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Exercise4-answer.ipynb",
"provenance": [],
"collapsed_sections": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "bVfoqS2eXjOV"
},
"source": [
"# Exercise 4\n",
"\n",
"This is the fourth hands-on exercise of the 2021 CDH entry level Python course at Utrecht University.\n",
"\n",
"The following program takes in a binary string of ones and zeros. It returns `True` if all bits are ones and `False` otherwise. However, there is a bug in the program. In the example below, the program returns `True` while there is clearly a zero in the string.\n",
"\n",
"1. Insert a breakpoint and step through the program to find out what is going wrong. Step multiple times through the program if necessary and do not stop until you fully understand what is going on.\n",
"2. Try to think of at least two ways in which you might solve the problem. Which is the safest way to be *very* sure that the problem will *never* happen again?\n",
"\n",
"If you have written a program with a bug during exercise 2 or 3, you may choose to use that program for this exercise instead."
]
},
{
"cell_type": "code",
"metadata": {
"id": "3N0mSvSyXWe4"
},
"source": [
"def only_ones(binary_string):\n",
" import pdb; pdb.set_trace()\n",
" for bit in binary_string:\n",
" if bit is '0':\n",
" return False\n",
" return True\n",
"\n",
"only_ones('1O1')"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "M0OZwOYEb2S1"
},
"source": [
"## Answer\n",
"\n",
"The problem is that the string contains the capital letter `'O'` instead of the digit `'0'`. Stepping with the debugger, you would eventually be at the line\n",
"\n",
"```python\n",
" if bit is '0':\n",
"```\n",
"\n",
"and running the command `p bit`, you would find that it prints `'O'`. At this point, you *might* notice that `bit` looks slightly different from the character in the condition.\n",
"\n",
"Otherwise, after going over this line a couple of times and starting to doubt yourself, you might try `p bit is '0'` and you would find that it prints `False`. At this point, you would certainly conclude that the string does not contain a zero, but something that looks similar to a zero.\n",
"\n",
"A solution that might quickly come to mind, is to fix the string. After all, a binary string of ones and zeros is not supposed to contain a capital letter `'O'`. This is indeed a mistake that needs to be fixed.\n",
"\n",
"However, this is not a complete solution. Next time somebody calls `only_ones`, they might again mistakenly include a character other than `'1'` or `'0'`, and the function would give the wrong answer again. This can be prevented by changing the condition:\n",
"\n",
"```python\n",
" if bit is not '1':\n",
"```\n",
"\n",
"Now, if the string contains *anything* other than a `'1'`, whether it's a `'0'` or something else, it will always returns `False`, as it should."
]
}
]
}
1 change: 1 addition & 0 deletions exercises/5_exercise.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"Exercise 5.ipynb","provenance":[],"collapsed_sections":[],"authorship_tag":"ABX9TyN61O3wVJQW63lhTuCcO6hc"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","metadata":{"id":"vJPGrtLJMaJd"},"source":["# Exercise 5 \n","\n","1. Upload your own dataset, or use `sample_data/california_housing_test.csv`\n","2. Use the example code to read the data from the CSV file\n","3. Print the following items:\n"," 1. The last row\n"," 2. The last column\n"," 3. The first row. If this is a header row, try if you can come up with a way to separate it from the data rows.\n","\n","Use best practises (write functions, document the code, etc)"]},{"cell_type":"code","metadata":{"id":"mIvIGXjLNFTp"},"source":[""],"execution_count":null,"outputs":[]}]}
Loading

0 comments on commit 45b1bbe

Please sign in to comment.