{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Lecture notes from first week\n", "Programming for the Behavioral Sciences" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "This week, basic concepts in Python are introducted. These concepts are important to understand the rest of the course, so make sure you understand everything presented here! The code below can be run in Spyder's iPython console.\n", "\n", "There are many good places to get more information and examples, e.g.,\n", "http://nbviewer.jupyter.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-1-Introduction-to-Python-Programming.ipynb\n", "\n", "There are many excellent introductions to Python on YouTube, so try typing \"introduction to python programming\" in the search field on youtube.com.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Variables and data types\n", "A variable is used to store information. It can be \n", "thought of as a 'container' used to \n", "refer to information/data while programming" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# Variables x, y, a, b, s\n", "x = 2 # In integer\n", "y = 17.0 # A float \n", "a = [2, 3, 4] # A list of length 3\n", "b = True # True or false\n", "s = 'hej' # A string\n", "t = (2, 4) # A tuple. Like a list, but cannot be modified" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that the hashtag sign '#' is used to write comments. Text that comes after the # is ignored.\n", "So, above we have variables of different types. What are these types and how are they different?\n", "You can read more about data types here:\n", "https://www.w3schools.com/python/python_datatypes.asp\n", "\n", "If we want to know the types of the above variables, the 'type' command can be used." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(int, float, list, bool, str, tuple)" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(x), type(y), type(a), type(b), type(s), type(t)\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also use the 'magic command' whos to get information about all variables currently in use" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Variable Type Data/Info\n", "-----------------------------\n", "a list n=3\n", "b bool True\n", "s str hej\n", "t tuple n=2\n", "x int 2\n", "y float 17.0\n" ] } ], "source": [ "%whos" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Variable operations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now lets try to use the above variables to understand what they do." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "19.0\n" ] } ], "source": [ "# Let's add two variables and print the result\n", "z = x + y\n", "print(z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Can we add other variable types as well?" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "([2, 3, 4], [2, 3, 4, 2, 3, 4], [2, 3, 4, 2, 3, 4, 2, 3, 4])" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a, a + a, a * 3" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "can only concatenate list (not \"tuple\") to list", "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[0;32m 1\u001b[0m \u001b[1;31m# This will give you an error, since your trying to add a list a = [2, 3, 4] with a tuple t = (2, 4)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ma\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mt\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: can only concatenate list (not \"tuple\") to list" ] } ], "source": [ "# This will give you an error, since your trying to add a list a = [2, 3, 4] with a tuple t = (2, 4)\n", "a + t" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "4 2\n" ] } ], "source": [ "# Remember, Python starts counting from zero, x[0] refers the first element of x. x[-1] refers to the last element of x\n", "print(t[0] + a[1])\n", "print(t[-1], x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "How can we use boolean variables then, and what do they mean?" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n", "True\n", "True\n", "False\n" ] } ], "source": [ "# Is this true? Notice the double equal sign for comparisons\n", "print(1==2)\n", "print(7==7)\n", "\n", "print(b)\n", "print(b is True)\n", "print(b is not True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Lists\n", "Lists are important and general data containers used heavily in Python. A list can contant pretty much any variable type. In a list, you can mix integers, floats, strings, and other lists." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['a', 1] 2\n" ] } ], "source": [ "l = ['a'] # make a list containing one element (a string 'a')\n", "l.append(1) # Append the integer 1 to the list\n", "print(l, len(l)) # Print the list and its length" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n", "[10, 12, 14, 16, 18]\n", "hej\n", "['h', 'e', 'j']\n" ] } ], "source": [ "another_list =list(range(20)) # Make a list with 20 elements from 0 to 19\n", "\n", "# Make another list with these properties\n", "start = 10\n", "stop = 20\n", "step = 2\n", "another_list_subsamples = list(range(start, stop, step))\n", "\n", "# Convert a string to a list (rember that s='hej')\n", "string_converted_to_list = list(s)\n", "\n", "# Print all the above in the cell\n", "print(another_list)\n", "print(another_list_subsamples)\n", "print(s)\n", "print(string_converted_to_list)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Strings\n", "Strings are used to deal with text and letters. \n", "More info here\n", "https://www.tutorialspoint.com/python/python_strings.htm\n", "\n", "f-strings are also really useful to format string:\n", "https://realpython.com/python-f-strings/" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hi there hi,there,!\n", "hi there! I am 30 years old\n" ] } ], "source": [ "# Let make a new string s0 = 'hi'. Let's define another one s2 = 'there'\n", "s0 = 'hi' # You can use both single (') and double (\") quotation marks to define string\n", "s1 = 'there'\n", "\n", "sentence0 = ' '.join([s0, s1]) # join the two strings with a space\n", "sentence1 = ','.join([s0, s1, '!']) # join the two strings with a comma (,)\n", "\n", "# Print the output\n", "print(sentence0, sentence1)\n", "\n", "# f-string example\n", "age = 30\n", "print(f'{s0} {s1}! I am {age} years old') # f denotes that it's an f-string." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Numpy arrays\n", "Arrays are data containers for numbers. NumPy (numerical python) is a package for dealing with numbers and arrays. It's not part of \"core\" Python, so to use it, we have to start by importing it. After importing numpy, type 'np.' followed by the tab-key. Then the commands available in the NumPy package become visible in a drop-down-list.\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "import numpy as np # Import numpy. Now we can use the Numpy functionalities \n", " # by its abbriviated name np (this name 'np' is arbitrary)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4, 5, 6] \n" ] } ], "source": [ "# Start by defining some numbers to work with\n", "a0 = [1, 2, 3]\n", "a1 = [4 ,5 ,6]\n", "\n", "# What would you expect if you added a + b\n", "c = a0 + a1\n", "print(c, type(a0), type(a1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Oops! This is perhaps not what you expected! c is not a + b = [5, 7, 9]. Why not? Well, you used lists (try type(a0), type(a1)). We need to tell Python it should interpret the lists as arrays!" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "c0 = [5 7 9]\n", "c1 = [5 7 9]\n" ] } ], "source": [ "# Make Python understand that we're working with numbers. Convert lists to arrays\n", "a0_array = np.array(a0)\n", "a1_array = np.array(a1)\n", "\n", "# No what's the output?\n", "c0 = np.array(a0_array) + np.array(a1_array)\n", "print(f'c0 = {c0}')\n", "\n", "# This also works, even though we use the lists. Why?\n", "c1 = np.add(a0, a1)\n", "print(f'c1 = {c1}')" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Let's move on to some useful examples of array generation and manipulation" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[4 8 5 9 2 5 1 0 9 9]\n", "4 [4 8] 9 [8 9 5]\n" ] } ], "source": [ "# Generate an array with 10 random integers between 0 and 9\n", "a = np.random.randint(0, 10, 10)\n", "print(a)\n", "\n", "# 'Slicing' an array means to select values from a range within the array\n", "#The basic slice syntax is i:j:k where i is the starting index, j is the stopping index, and k is the step\n", "a[0] # Selects first element\n", "a[0:2] # Selects first two elements. Note that the value at index 2 is not taken, just values at indeces 0 and 1\n", "a[-1] # Selects last element\n", "a[1:7:2]# Selects every second values from index 1 to 7\n", "print(a[0], a[0:2], a[-1], a[1:7:2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, this is similar to the operations we performed on the lists." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[4 2 1 0] (array([0, 4, 6, 7], dtype=int64),)\n" ] } ], "source": [ "# Even more examples on how you can select elements from an array\n", "a[np.array([0, 1, -2, -1])] # Two first and two last\n", "a[a < 5] # Returns all values where a is less than 5\n", "boolean_vector = a < 5\n", "np.where(a < 5) # Positions were a < 5\n", "values_less_than_5, positions_where_values_are_less_than_5 = a[a < 5], np.where(a < 5)\n", "print(values_less_than_5, positions_where_values_are_less_than_5)\n", "\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[6 4 5 8 6]\n", " [3 3 2 0 0]\n", " [1 1 6 0 9]\n", " [1 4 8 1 0]]\n" ] } ], "source": [ "# A two dimensional array (4 rows, 5 columns) with random integres between 0 and 9\n", "v = np.random.randint(0, 10, (4 , 5))\n", "print(v)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### For-loops\n", "For-loops are used to **repeat** operations, to make computers quickly perform tasks that are repetitive and/or boring for humans. Let's start with an example you can do yourself with pen and paper: draw a square. The instructions for doing so could be (test yourself):\n", "\n", "1. draw a straight line 1 unit long. Turn 90 deg right. \n", "2. draw a straight line 1 unit long. Turn 90 deg right. \n", "3. draw a straight line 1 unit long. Turn 90 deg right. \n", "4. draw a straight line 1 unit long. Turn 90 deg right. \n", "\n", "A more compact way of writing this would be, for instance,\n", "\n", "repeat(4){ forward 1 unit; turn right}\n", "\n", "Likewise, the code for drawing a staircase would be,\n", "\n", "repeat(x){up 1 unit; turn right; forward 1 unit; turn left}\n", "\n", "x is the number of steps in the staircase.\n", "\n", "In Python, the syntax for a for-loop is the following." ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "source": [ "# A very simple for-loop (the letter 'i' is often used as a counter)\n", "n = 15 # First run this as is. Then replace 10 by n below. Test to change the value of n and see what happens.\n", "for i in range(10):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try to explain in words to yourself what happend in the above for-loop." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "P\n", "g\n", "p\n", "o\n", "e\n", "n\n", "r\n" ] } ], "source": [ "# loop over a letter string\n", "letter_string = 'Programming is an important tool for researchers in behaviour sciences'\n", "\n", "# Print every 10th letter\n", "for letter in letter_string[slice(0, len(letter_string), 10)]:\n", " print(letter)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z'] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'y', 'z']\n" ] } ], "source": [ "# Make list of the letters in the alphabet\n", "alphabet = 'abcdefghijklmnopqrstuvxyz'\n", "\n", "# first way\n", "L1 = list(alphabet)\n", "\n", "# Second way (using for loop)\n", "L2 = []\n", "for l in alphabet:\n", " \n", " # I don't like the letter x, so let's exclude it from the list\n", " if l != 'x': # != means NOT equal to\n", " L2.append(l)\n", "\n", "print(L1, L2)" ] } ], "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.9.12" } }, "nbformat": 4, "nbformat_minor": 1 }