{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lesson A2 – Working with numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's try to put Python to some practical use. The possibilities you have with this *general purpose* language are huge, but at the very least, we can use the Python interpreter as a fancy pocket-calculator. You can find what we talk about here also in different form in the official Python [beginners-tutorial](https://docs.python.org/3/tutorial/introduction.html)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Types of numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numbers can be represented in Python by the data types:\n", "\n", " - `int` (whole numbers)\n", "\n", " - `float` (floating point numbers)\n", "\n", " - `complex` (complex numbers)\n", "\n", "We can access the type of a number by using the function `type`." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# integer\n", "i = 1\n", "print(type(i))" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# floating point number\n", "f = 0.5\n", "print(type(f))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Trailing zeros in floats can be omitted. You can also store\n", "a whole number as a float by explicit use of a decimal point." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# whole number as floating point number\n", "f = 1.\n", "print(type(f))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To create a complex number we can make a number imaginary by using the letter j." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# complex number\n", "c = 2 + 6j\n", "print(type(c))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can get the real and the imaginary part separately, where both parts\n", "are considered floats." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.0 \n", "6.0 \n" ] } ], "source": [ "print(c.real, type(c.real))\n", "print(c.imag, type(c.imag))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Operations with numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In Python, you can use the operators `+`, `-`, `*`, and `/` to combine objects. For numbers,\n", "these behave like you would expect it from arithmetic operators." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "0\n" ] } ], "source": [ "# Add/Substract numbers\n", "print(1 + 1)\n", "print(1 - 1)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "1.0\n" ] } ], "source": [ "# Multiply/divide numbers\n", "print(1 * 2)\n", "print(2 / 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note, that Python automatically returns a float when we divide an integer by another." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(2 / 2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can explicitly use integer division, in which case the result will be floored (rounded down) to the next lower integer. " ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 \n" ] } ], "source": [ "print(3 // 2, type(3 // 2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Furthermore, there is the % operator (the modulo operator) that gives you the rest of an integer division." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 \n" ] } ], "source": [ "print(3 % 2, type(3 % 2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we mix integers with floats, Python treats both numbers as floats,\n", "which is the broader number definition. You can say `float` is a wider\n", "type than `int`." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.0 \n" ] } ], "source": [ "print(1 + 1., type(1 + 1.))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly, we get a complex number when we combine floats and complex numbers." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(2+1j) \n" ] } ], "source": [ "print(1. + (1 + 1j), type(1. + (1 + 1j)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This even works when the imaginary part of the number is zero." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(2+0j) \n" ] } ], "source": [ "print(1.0 + (1 + 0j), type(1.0 + (1 + 0j)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Raising a number to a higher power can be done in two ways." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n", "8\n" ] } ], "source": [ "print(2 ** 3)\n", "print(pow(2, 3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With these basic operations you can now solve simple equations, e.g. you can\n", "compute the Coulomb repulsion of two positive elemental charges at a given distance. Python\n", "understands floating point numbers in scientific notation: $1\\mathrm{e}2 = 1 \\times 10^2$. " ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Coulomb interaction: 2.3097635999999995e-10 N\n" ] } ], "source": [ "r = 1e-9 # m = 1 nm, Distance\n", "ke = 9e9 # N * m**2 * C**−2, Force constant in vacuum\n", "q1 = q2 = 1.602e-19 # C, Charges\n", "\n", "F = (ke * q1 * q2) / r**2 # Calculate force\n", "print(\"Coulomb interaction: \", F, \"N\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Advanced topics" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Special values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The probably most frequently used number type for computations is float. It\n", "is the type of choice to represent real numbers. Besides actual real numbers\n", "Python knows a few special numbers that are not really numbers." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "no_number = float('nan') # Python representation of \"not-a-number\"\n", "type(no_number)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "nan\n" ] } ], "source": [ "print(no_number + 1)\n", "# Acts as a placeholder that can be used in computations" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "inf = float('inf') # Python representation of infinity\n", "type(inf)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "minf = float('-infinity') # Python representation of -infinity\n", "type(minf)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "inf\n" ] } ], "source": [ "print(inf + 1)\n", "# Can be used in computations" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "nan\n" ] } ], "source": [ "print(inf + minf)\n", "# Can be used in computations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Type conversion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To force a number to be of a certain type we can use\n", " \n", " - `int()`\n", " \n", " - `float()`\n", " \n", " - `complex()`" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(int(2.1)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But this is not always possible..." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "can't convert complex to int", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m6j\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: can't convert complex to int" ] } ], "source": [ "print(type(int(2 + 6j)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We are getting another type of error here. A `TypeError` occurs when you\n", "try to do something with an object that is not permitted by its type." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is always possible to convert a number into a str using `str()`. If a string\n", "happens to be actually a number, it can also converted using the above functions." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10.1\n" ] } ], "source": [ "print(str(10.1))" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n" ] } ], "source": [ "print(int(\"10\"))" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "invalid literal for int() with base 10: '10.1'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"10.1\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mValueError\u001b[0m: invalid literal for int() with base 10: '10.1'" ] } ], "source": [ "print(int(\"10.1\"))" ] } ], "metadata": { "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.6.10" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": true, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "263.6px" }, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }