{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. Data Types\n", "\n", "Use a locally installed editor like Spyder or Visual Studio Code. If you want to try out coding without installing anything, try this online editor: https://www.pythonanywhere.com/try-ipython/\n", "\n", "## Code comments\n", "In order to explain the code, comments in Python can be made by preceding a line with a hashtag `#`. Everything on that particular line will then not be interpreted as part of the code:\n", "\n", "```python\n", "# This is a comment and will not be interpreted as code\n", "```\n", "\n", "## Data Types\n", "The basic data types in Python are illustrated below." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Integers (`int`)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# Integers\n", "a = 2\n", "b = 239" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Floating point numbers (`float`)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# Floats\n", "c = 2.1\n", "d = 239.0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Strings (`str`)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "e = 'Hello world!'\n", "my_text = 'This is my text'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Both `\"` and `'` can be used to denote strings. If the apostrophe character should be part of the string, use `\"` as outer boundaries:\n", "~~~~python\n", "\"Barack's last name is Obama\"\n", "~~~~\n", "Alternatively, `\\` can be used as an *escape* character:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"Barack's last name is Obama\"" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'Barack\\'s last name is Obama'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that strings are ***immutable***, which means that they can't be changed after creation. They can be copied, then manipulated and thereafter saved into a new variable though." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Boolean (`bool`)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "x = True\n", "y = False" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Python is dynamically typed language\n", "As you might have noticed, Python does not require you to declare the type of a variable before creating it. This is because Python is a *dynamically typed language*. \n", "\n", "To create a variable `a` in a *statically typed language*, it would go something like (C++):\n", "> ~~~c++\n", "> int a\n", "> a = 5\n", "> ~~~\n", "\n", "You might also have seen this when using VBA with *Option Explicit* enabled, where it would be `Dim a As Integer` and then `a = 5`. If the variable type is not declared beforehand in such languages, an error will be thrown.\n", "This is not the case in Python. It automatically figures out which type to assign to each variable in the background.\n", "\n", "This does not mean that Python is 'smarter' than other languages, it's purely an implementation choice from the author of the language to make it behave this way. And it has both advantages and drawbacks.\n", "\n", "Dynamic typing also means that variables can change types throughout the program, so somthing like this is valid:\n", "> ~~~python\n", "a = 5\n", "a = 'Hi'\n", "> ~~~\n", "\n", "Which can be both a blessing and a curse. The flexibility is nice, but it can lead to unexpected code behavior if variables are not tracked. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Calculations with data types" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Standard calculator-like operations\n", "Most basic operations on integers and floats such as addition, subtraction, multiplication work as one would expect:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 * 4" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.4" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 / 5" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10.5" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3.1 + 7.4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exponents \n", "Exponents are denoted by `**`:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2**3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> **Watch Out**: The `^` operator is **not** used for exponentiation. Instead, it's a `Binary XOR operator` (whatever that is)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Floor division\n", "Floor division is denoted by `//`. It returns the integer part of a division result (removes decimals after division):" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "10 // 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Modulo\n", "Modulo is denoted by `%`. It returns the remainder after a division:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "10 % 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Operations on strings\n", "Strings can be **added** (concatenated) by use of the addition operator `+`:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Bruce Wayne'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'Bruce' + ' ' + 'Wayne'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Multiplication** is also allowed:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'aaa'" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'a' * 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Subtraction** and **division** are not allowed: " ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unsupported operand type(s) for /: 'str' and 'int'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;34m'a'\u001b[0m \u001b[1;33m/\u001b[0m \u001b[1;36m3\u001b[0m \u001b[1;31m# Division results in error\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for /: 'str' and 'int'" ] } ], "source": [ "'a' / 3 # Division results in error" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unsupported operand type(s) for -: 'str' and 'str'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;34m'a'\u001b[0m \u001b[1;33m-\u001b[0m \u001b[1;34m'b'\u001b[0m \u001b[1;31m# Subtraction results in error\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for -: 'str' and 'str'" ] } ], "source": [ "'a' - 'b' # Subtraction results in error" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Printing strings with variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There is quite often a need for printing a combination of static text and variables. This could e.g. be to output the result of a computation. Often the best way is to use the so-called **f-strings**. See examples below." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Multiplication: a * b = 2 * 27 = 54\n", "Division: a / b = 2 / 27 = 0.07407407407407407\n" ] } ], "source": [ "# Basic usage of f-strings\n", "a = 2\n", "b = 27\n", "print(f'Multiplication: a * b = {a} * {b} = {a*b}')\n", "print(f'Division: a / b = {a} / {b} = {a/b}')" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Division: a / b = 2 / 27 = 0.074\n" ] } ], "source": [ "# f-strings with formatting for number of decimal places\n", "print(f'Division: a / b = {a} / {b} = {a/b:.3f}') # The part ':.xf' specfifies 'x' decimals to be printed " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Both variables and complex computations can be inserted inside the curly brackets to be printed." ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Computation insde curly bracket: 316.6808510638298\n" ] } ], "source": [ "print(f'Computation insde curly bracket: {122**2 / 47}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Function: `len()`\n", "The `len()` function returns the length of a sequence, e.g. a string:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len('aaa')" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len('a and b') # Spaces are also counted" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Some string methods\n", "A string object can be interacted with in many ways by so-called ***methods***. Some useful methods are shown below:\n" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "name = 'Edward Snowden'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `string.replace()`\n", "Replaces characters inside a string:\n", "~~~python\n", "string.replace('old_substring', 'new_substring')\n", "~~~" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Ed Snowden'" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "name.replace('Edward', 'Ed')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Recall that strings are ***immutable***. They can be copied, manipulated and saved to a new variable. But they can't be changed per se. This concept transfers to other more complex constructs as well.\n", "\n", "Thus, the original string called `name` is still the same:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Edward Snowden'" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In order to save the replacement and retain the name of the variable, we could just reassign it to the same name:" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "name = name.replace('Edward', 'Ed') " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Internally, the computer gives this new `name` variable a new id due to the immutability, but for us this does not really matter. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `string.endswith()`\n", "This method might be self explanatory, but returns a ***boolean*** (`True` of `False`) depending on whether or not the strings ends with the specified substring.\n", "\n", "~~~python\n", "string.endswith('substring_to_test_for')\n", "~~~" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "name.endswith('g')" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "name.endswith('n')" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "name.endswith('den')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `string.count()`\n", "Counts the number of occurences of a substring inside a string:\n", "~~~python\n", "string.count('substring_to_count')\n", "~~~\n", "\n" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "text = 'This is how it is done'\n", "text.count('i')" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "text.count('is')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The match is case sensitive:" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "text.count('t')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conditionals and code indendation\n", "In Python, code blocks are separated by use of indentation. See the defintion of an `if`-statement below:\n", "\n", "### Syntax of conditional blocks\n", " \n", "```python\n", "if condition:\n", " # Code goes here (must be indented!)\n", " # Otherwise, IndentationError will be thrown\n", "\n", "# Code placed here is outside of the if-statement \n", "```\n", "\n", "Where evaluation of `condition` must return a boolean (`True` or `False`).\n", "\n", "\n", "> **Remember:**\n", "> 1. The `:` ***must*** be present after `condition`.\n", "> 2. The line immediately after `:` ***must*** be indented. \n", "> 3. The `if`-statement is ***exited by reverting the indentation*** as shown above.\n", "\n", "This is how Python interprets the code as a block. \n", "\n", "The same indentation rules are required for all types of code blocks, the `if`-block above is just an example. Examples of other types of code blocks are `for` and `while` loops, functions etc.\n", "\n", "All editors will automatically make the indentation upon hitting enter after the `:`, so it doesn't take long to get used to this. \n", "\n", "### Comparison to other languages\n", "In many other programming languages indentation is not required. It is however still used as good practice to increase code readability. Instead of indentation, code blocks are denoted by encapsulating code in characters like `()`, `{}` etc.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conditional statements - examples\n", "\n", "### `if`-statements\n", "An `if`-statement has the following syntax:" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "x is larger than 1\n" ] } ], "source": [ "x = 2\n", "if x > 1:\n", " print('x is larger than 1')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `if` / `else`-statements" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "y is less than or equal to 1\n" ] } ], "source": [ "y = 1\n", "if y > 1:\n", " print('y is larger than 1')\n", "else:\n", " print('y is less than or equal to 1')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `if` / `elif` / `else`" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "z is less than 1\n" ] } ], "source": [ "z = 0\n", "if z > 1:\n", " print('z is larger than 1')\n", "elif z < 1:\n", " print('z is less than 1')\n", "else:\n", " print('z is equal to 1')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An unlimited number of `elif` blocks can be used in between `if` and `else`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Find the length of the following string:\n", "> ~~~~python\n", "> s = \"Batman's real name is Bruce Wayne\"\n", "> ~~~~" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise 2\n", "Test if `s` from above has *\"Wayne\"* as last characters (should return `True` of course)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise 3\n", "Print the following sentence using an `f-string`:\n", "\n", "```python\n", "'The string s has a length of {insert_length_of_s} items.'\n", "```\n", "\n", "Use `s` from above." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise 4\n", "Use the `count()` method to print the number of ***e***'s in the string `s` form above." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise 5\n", "Use the `replace()` method to replace `Ø` with `Y` in the following string:\n", "\n", ">~~~python\n", "string1 = '33Ø12'\n", ">~~~\n", "\n", "Save the new string in a variable `string2` and print the following sentence:\n", "```python\n", "'The string {insert_string1} was replaced by {insert_string2}'\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise 6\n", "If the string below has more than 100 characters, print *\"String has more than 100 characters\"*, otherwise print *\"String has less than or exactly 100 characters\"*.\n", "~~~python\n", "dummy_string = 'Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups.'\n", "~~~" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise 7\n", "Print the number of space characters in `dummy_string` from above. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise 8\n", "Create the variables\n", "\n", "```python\n", "letter1 = 'e'\n", "letter2 = 'm'\n", "```\n", "\n", "Convert this pseudo code to a Python program:\n", "\n", "```python\n", "if there are more occurrences of letter1 than letter2 in dummy_string:\n", " print(\"There are more {insert_letter1}'s than {insert_letter2}'s\")\n", " \n", "elif there are more occurrences of letter2 than letter1 in dummy_string:\n", " print(\"There are more {insert_letter2}'s than {insert_letter1}'s\")\n", "\n", "else:\n", " print(\"There are exactly the same number {insert_letter1}'s and {insert_letter2}'s\")\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise 9\n", "Test the program you wrote above with different combinations of letters for the variables `letter1` and `letter2`. \n", "\n", "If you are still with us at this point you can try to implement a print message of the actual number of occurrences." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "# 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": 34, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import HTML\n", "HTML(''.format(open('../css/cowi.css').read()))" ] } ], "metadata": { "hide_input": false, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.4" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autoclose": false, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Table of Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": true } }, "nbformat": 4, "nbformat_minor": 2 }