{ "cells": [ { "cell_type": "markdown", "id": "0608355c", "metadata": {}, "source": [ "# Introduction to Python\n", "\n", "Python is a very simple language, and has a very straightforward syntax. In most cases, it should feel like writing down exactly what you want the computer to do.\n", "\n", "There are two major Python versions, Python 2 and Python 3. For our purposes we can ignore Pyhton 2 and focus on the newer version 3 (but keep in mind that some older information online might be based on Pyhton 2)." ] }, { "cell_type": "markdown", "id": "2b3a7a99", "metadata": {}, "source": [ "## The Print statement, Hello World!\n", "\n", "One of the most basic tasks is to print some text output. This is not only useful to retreive the result of a program, but also as a simple step to diagnose problems. In Python this is very simple:" ] }, { "cell_type": "code", "execution_count": 1, "id": "358050ed", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This line will be printed.\n" ] } ], "source": [ "print(\"This line will be printed.\")" ] }, { "cell_type": "markdown", "id": "c5d548ee", "metadata": {}, "source": [ "Note that `print` acts as a function (more later), and prints whatever is in the brackets. If we want to print some text we have to surround it by `\"\"`. One of the most basic programs are 'Hello World!' programs, that can be used to test a new programming environment by writing a program that prints the line 'Hellp World!'. This is very simple in python, why don't you give it a try:" ] }, { "cell_type": "code", "execution_count": null, "id": "d44e2e54", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "870679d0", "metadata": {}, "source": [ "## Variables and basic math, import\n", "\n", "To do something useful, most programmig languages allow you to save numerical values in variables and perform basic math operations on those variables:" ] }, { "cell_type": "code", "execution_count": 4, "id": "df1cc960", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7\n" ] } ], "source": [ "a = 3\n", "b = 4\n", "c = a + b\n", "print(c)" ] }, { "cell_type": "markdown", "id": "ea94ee71", "metadata": {}, "source": [ "When we want to calculate more interesting functions, we have to add additional packages to our program. This is done using the `import` statement:" ] }, { "cell_type": "code", "execution_count": 5, "id": "8e1e54e4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5.0\n" ] } ], "source": [ "import math as m\n", "\n", "c = m.sqrt(a**2 + b**2)\n", "print(c)" ] }, { "cell_type": "markdown", "id": "6528187f", "metadata": {}, "source": [ "Note that `a` and `b` were still defined from the previous cell (if you opened the notebook and right away executed this cell, it will not have worked and you will first have to execute the previous one), and we overrode the value stored in `c`. We also used the shorter `m` to abbreviate the `math` module in the `import` statement. The `**` is Pyhton's native syntac to raise a number to some power." ] }, { "cell_type": "markdown", "id": "7eb0e522", "metadata": {}, "source": [ "## Indentation and if\n", "\n", "An important part of any programming language are `if` statements. They will evaluate some expression that can be either `True` of `False`, and only execute the next bit of code if it is `True`. In Pyhton, the expression to be evaluated comes right after an `if`, and is terminated by a colon `:`. To mark the code that depends on the if statement, Python uses indentation:" ] }, { "cell_type": "code", "execution_count": 7, "id": "177c724f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hi Tom.\n" ] } ], "source": [ "name = 'Tom'\n", "if name == 'Tom':\n", " print('Hello Tom.')\n", "elif name == 'Tim':\n", " print('Hello Tim.')\n", "else:\n", " print('Hello, Unknown.')" ] }, { "cell_type": "markdown", "id": "b843e025", "metadata": {}, "source": [ "Note how we have used `elif` to provide code that is executed if the first expression is not true, but the second is, and `else` for code that is executed if none of the `if` statements are true.\n", "\n", "As a side note, if our goal was to actually print 'Hello' followed by whatever name is saved in `name`, Python provides a number of ways to format output with variables:" ] }, { "cell_type": "code", "execution_count": 11, "id": "617645bb", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Tom\n", "Hello Tom.\n", "Hello Tom.\n", "Hello Tom.\n", "Hello, name='Tom'.\n" ] } ], "source": [ "print('Hello',name)\n", "print('Hello {}.'.format(name))\n", "print('Hello {NAME}.'.format(NAME=name))\n", "print(f'Hello {name}.')\n", "print(f'Hello, {name=}.')" ] }, { "cell_type": "markdown", "id": "5a95ed14", "metadata": {}, "source": [ "This works with 'strings' (the variables where we saved text), but also numbers:" ] }, { "cell_type": "code", "execution_count": 14, "id": "5ee0f689", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a = 3\n", "b=4\n", "3^2 + 4^2 = 25\n" ] } ], "source": [ "a = 3\n", "b = 4\n", "print('a = ',a)\n", "print(f'{b=}')\n", "print(f'{a}^2 + {b}^2 = {a**2+b**2}')" ] }, { "cell_type": "markdown", "id": "e3c96892", "metadata": {}, "source": [ "## Lists and for-loops\n", "\n", "Another concept you will find helpful are lists, that can save multiple values." ] }, { "cell_type": "code", "execution_count": 16, "id": "6f7998c4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 5, 6]\n" ] } ], "source": [ "l = [1,2,5,6]\n", "print(l)" ] }, { "cell_type": "markdown", "id": "b4a393f8", "metadata": {}, "source": [ "We can access the individual elements by their index (note that the first element has index `0`, not `1`):" ] }, { "cell_type": "code", "execution_count": 18, "id": "5a292e8e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "l[0]=1\n", "l[2]=5\n" ] } ], "source": [ "print(f'{l[0]=}')\n", "print(f'{l[2]=}')" ] }, { "cell_type": "markdown", "id": "94a7e7fa", "metadata": {}, "source": [ "If we want to execute some code for every element in a list, we can use a `for` loop. The syntax is similar to the `if` statements from earlier:" ] }, { "cell_type": "code", "execution_count": 19, "id": "38bc6d09", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "element=1\n", "element=2\n", "element=5\n", "element=6\n" ] } ], "source": [ "for element in l:\n", " print(f'{element=}')" ] }, { "cell_type": "markdown", "id": "c2b2bcad", "metadata": {}, "source": [ "Sometimes we just need a list with numbers in their normal order. We can get those with the `range` function:" ] }, { "cell_type": "code", "execution_count": 21, "id": "0157aac7", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n" ] } ], "source": [ "print(list(range(10)))" ] }, { "cell_type": "markdown", "id": "2c9a92e9", "metadata": {}, "source": [ "With this we can for example do the following:" ] }, { "cell_type": "code", "execution_count": 22, "id": "487293c3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "element 0 = 1.\n", "element 1 = 2.\n", "element 2 = 5.\n", "element 3 = 6.\n" ] } ], "source": [ "for i in range(len(l)):\n", " print(f'element {i} = {l[i]}.')" ] }, { "cell_type": "markdown", "id": "8ac664ce", "metadata": {}, "source": [ "Can you explain how this works? Tip: in Python it is always easy to get help:" ] }, { "cell_type": "code", "execution_count": 23, "id": "82825fc1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function len in module builtins:\n", "\n", "len(obj, /)\n", " Return the number of items in a container.\n", "\n" ] } ], "source": [ "help(len)" ] }, { "cell_type": "markdown", "id": "ba86d86c", "metadata": {}, "source": [ "## Functions\n", "\n", "One of the keys to efficient programming in Python is the used of functions to avoid writing the same code over and over again. A function takes some arguments and then executes a piece of code depending on those:" ] }, { "cell_type": "code", "execution_count": 24, "id": "07748c58", "metadata": {}, "outputs": [], "source": [ "def SayHello(name):\n", " \"\"\"Prints the string 'Hello {name}'.\n", " \n", " This comment will be shown as help for this function.\n", " It is a good idea to write an explanation of how your\n", " function will work here!\n", " \"\"\"\n", " print(f'Hello {name}!')" ] }, { "cell_type": "code", "execution_count": 26, "id": "54c05371", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Tom!\n", "Hello Tim!\n" ] } ], "source": [ "SayHello('Tom')\n", "SayHello('Tim')" ] }, { "cell_type": "code", "execution_count": 27, "id": "898e72d5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function SayHello in module __main__:\n", "\n", "SayHello(name)\n", " Prints the string 'Hello {name}'.\n", " \n", " This comment will be shown as help for this function.\n", " It is a good idea to write an explanation of how your\n", " function will work here!\n", "\n" ] } ], "source": [ "help(SayHello)" ] }, { "cell_type": "markdown", "id": "626a1189", "metadata": {}, "source": [ "Ofte we will want our functions to return some value or object that we want to use later in our code. For example:" ] }, { "cell_type": "code", "execution_count": 28, "id": "91e31068", "metadata": {}, "outputs": [], "source": [ "def RemoveTrailingWhitespace(inlist):\n", " \"\"\"Removes all trailing whitespace from the strings in list inlist.\n", " \n", " Returns a list with the elements of inlist, but with trailing \n", " whitespaces removed from the strings.\n", " No non-string elements are allowed in inlist.\n", " \"\"\"\n", " retlist = [l.strip() for l in inlist]\n", " return retlist" ] }, { "cell_type": "code", "execution_count": 29, "id": "ba066170", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Tim', 'Tom', 'Tim and Tom']\n" ] } ], "source": [ "print(RemoveTrailingWhitespace([' Tim', 'Tom ', 'Tim and Tom ']))" ] }, { "cell_type": "markdown", "id": "a811c53e", "metadata": {}, "source": [ "## Conclusion\n", "\n", "That should cover the most important things we will need over the next weeks. There is a lot more material online, you can for example find a much more complete tutorial here https://www.learnpython.org." ] }, { "cell_type": "code", "execution_count": null, "id": "fd070ff2", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10.12" } }, "nbformat": 4, "nbformat_minor": 5 }