{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Python basics\n",
"\n",
"## Variables\n",
"In python, as in many programming language, objects are stored in variables.\n",
"* A value is assigned to a variable using the `=` sign. \n",
"* **Warning:** unlike in mathematics, the `=` sign in python is directional: the variable name must always be on the left of the `=`, and the value to assign to the variable on the right. \n",
" Example:\n",
" ```python\n",
" a = 23 # is a valid assignment.\n",
" 8 = b # is NOT a valid assignment.\n",
" ```\n",
"\n",
"In python variables names must adhere to these restrictions:\n",
"* must be composed of uppercase, lowercase letters `A-Z`, `a-z`, digits `0-9` , and the underscore character `_`.\n",
"* the first character of a variable name cannot be a digit. E.g. `file_1` is a valid variable name, but `1_file` is not.\n",
"* by convention, variable names starting with a single or double underscore `_`/`__` are reserved for \"special\" variables (class private attributes, \"magic\" variables).\n",
"\n",
"\n",
"> **pro tip**: using explicit variable names makes your code more understandable to others, as well as you-from-the-future. For instance `input_file` is better than `iptf`."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"myVariable = 35 # assign the value 35 to variable \"myVariable\".\n",
"var_a = 2.3 # assign the value 2.3 to variable \"a\".\n",
"var_b = var_a # assign to value of \"var_a\" to \"var_b\".\n",
"\n",
"# By the way, text located after a \"#\" character - just like this line - are comments. \n",
"# Comments are text that will not be executed, but is useful for code documentation\n",
"print(myVariable)\n",
"print(var_a)\n",
"print(var_b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
\n",
"\n",
"## Functions\n",
"Another very important concept in Python - as in most programming language - are **functions**.\n",
"* functions are a re-usable blocks of code that have been given a name and are ready to perform an action. How to define your your own functions will be detailed later in this course.\n",
"* functions can be written to perform anything, from the simplest task to the most complex.\n",
"* to call a function, one uses its name followed by parentheses `()`, which contain an eventual set of arguments (arguments are the variables that the function needs to work on)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### The help function - your best friend in Python\n",
"In python, almost any object or function is extensively documented: what it is, what it does, how to use it, ... \n",
"We access this help using the `help()` function, which takes as argument the object we want to get help with."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on built-in function print in module builtins:\n",
"\n",
"print(...)\n",
" print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n",
" \n",
" Prints the values to a stream, or to sys.stdout by default.\n",
" Optional keyword arguments:\n",
" file: a file-like object (stream); defaults to the current sys.stdout.\n",
" sep: string inserted between values, default a space.\n",
" end: string appended after the last value, default a newline.\n",
" flush: whether to forcibly flush the stream.\n",
"\n"
]
}
],
"source": [
"## let's try to look up the help page of the print function that you have already encountered.\n",
"help(print)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It tells us that:\n",
" * `print` is a function.\n",
" * it \"Prints the values to a stream, or to sys.stdout by default.\", here a stream can be a file, sys.stdout is the console -> so the function prints to the console (and possibly to a file).\n",
" * its arguments are the things that will be printed.\n",
" * it has 4 optional arguments that refines its use.\n",
"\n",
"Let's try to apply our new knowledge of the `print` function :"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"test\n",
"test 42\n",
"test/42\n"
]
}
],
"source": [
"print('test') # simple usage.\n",
"print('test' , 42) # we can make it print several values. by default, they are separated by spaces.\n",
"print('test' , 42 , sep='/') # the sep argument can be used to change the separator between values."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Don't hesitate to use the `help` function on any object or function to understand how they work.**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reading and understanding errors\n",
"\n",
"Unless you are a perfect human being, your code will contain some error at some point. \n",
"Errors ~~can sometimes be~~ are frustrating, but they are unavoidable, and the best way to correct them is to actually read and try to understand them.\n",
"\n",
"Here is an error example:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'var_c' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mvar_a\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m42\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mvar_b\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mvar_a\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mvar_c\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'var_c' is not defined"
]
}
],
"source": [
"var_a = 42\n",
"var_b = var_a + 3\n",
"print(var_c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The first line indicates the **type** of ther error. In our example we got a `NameError`, which means that a name has not been found. \n",
"If you want to know more about a certain error type, you can use the help function on it: `help(NameError)`.\n",
"\n",
"The following lines point out the line where the error occured, which is very useful when if have hundreds of them. Here the error occured on line `3`, the line of the `print` statement.\n",
"\n",
"Finally, we have `NameError: name 'var_c' is not defined`, which points out that we tried to print the variable `var_c` when that variable does not exists (i.e., that name is not defined).\n",
"\n",
"> Arguably, being able to **read and understand errors** and being able to **read the help** accounts for ~50% of \"coding skills\"....\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Micro exercise** : look at the error given by the following code. Try to understand it and modify the code accordingly."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "unsupported operand type(s) for +: 'int' and 'str'",
"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[0;36m42\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m\"a\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'"
]
}
],
"source": [
"42 + \"a\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
\n",
"\n",
"## Object types: simple types\n",
"Python divides objects into several categories which are called **type**. \n",
"There exist plenty of type (is it even common to define your own new type), but there a few very common ones - known as **built-in** types - that you ought to know.\n",
"* `bool`: boolean/logical values, either `True` or `False`, like a 0 or 1\n",
"* `int` : integer number\n",
"* `float`: floating point number\n",
"\n",
"To know the type of an object, use the `type()` function. \n",
"**Note:** contrary to some other languages (like C++ for instance) variables in python are not restricted to a single type and can be reassigned another type of value at any time."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# In this example we successively assign different values and types to the variable \"a\".\n",
"# boolean\n",
"a = True\n",
"print(\"type of a is:\", type(a))\n",
"\n",
"# float\n",
"a = 4.2\n",
"print(\"type of a is:\", type(a))\n",
"\n",
"# integer\n",
"a = 42\n",
"print(\"type of a is:\", type(a))\n",
"print(\"type of 42 is:\", type(42))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Type conversion is (often) fairly easy : juste use the type name as a function"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Convert a integer to a float:\n",
"print(\"type of a before conversion:\", type(a))\n",
"a = float(a)\n",
"print(\"type of a after conversion:\", type(a))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Mirco Exercise** : convert `a` back to an integer (`int`). Look up the `help` for integers."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
\n",
"\n",
"## Operators\n",
"Now that you have variables containing objects of a certain _**type**_, you can begin to play with them using operators.\n",
"\n",
"### Arithmetic operators \n",
"You know most of these already:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print( 3 + 7 ) # + : addition\n",
"print( 1.1 - 5 ) # - : substraction\n",
"print( 5 / 2 ) # / : division\n",
"print( 5 // 2 ) # //: integer division\n",
"print( 5 * 2 ) # * : multiplication\n",
"print( 2 ** 4 ) # **: power\n",
"print( 5 % 2 ) # % : modulus (remainder of the division)\n",
"\n",
"# Variables can be used there as well:\n",
"x = 4\n",
"y = 16 * x**2 - 2 * x + 0.5 \n",
"print(y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now you can use Python as a fancy calculator!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Bonus:** when modifying the value of a variable, you can use the following shortcut operators:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 0\n",
"\n",
"# Same as a = a + 3\n",
"a += 3\n",
"print(\"The value of 'a' is now:\", a)\n",
"\n",
"# Same as a = a - 1\n",
"a -= 1 \n",
"print(\"The value of 'a' is now:\", a)\n",
"\n",
"# Same as a = a * 3\n",
"a *= 3\n",
"print(\"The value of 'a' is now:\", a)\n",
"\n",
"# Same as a = a / 2\n",
"a /= 2\n",
"print(\"The value of 'a' is now:\", a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
\n",
"\n",
"### Comparison operators\n",
"\n",
"These operators return a `bool` value (`True` or `False`)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 5\n",
"print(\"is a equal to 1?:\", a == 1)\t\t\t # == : equality\n",
"print(\"is a different to 13.37?:\", a != 13.37)\t # != : inequality\n",
"print(\"is a greater than 5?:\", a > 5 )\t\t\t\t# > : larger than\n",
"print(\"is a lower than 10?:\", a < 10 )\t\t\t\t# < : lower than\n",
"print(\"is a above 5?:\", a >= 5 )\t\t\t\t\t# <= : lower or equal\n",
"print(\"is a lower than 10?:\", a <= 10 )\t\t \t# >= : larger or equal\n",
"\n",
"print(\"is a equal to '5'?:\", a == '5') # note that comparisons are sensible to types, so this evaluates to False.\n",
"\n",
"# boolean (resulting from comparisons) can be combined using 'and' or 'or'\n",
"print(\"'and' requires both elements to be True:\" , True and ( 1 + 1 != 2 ) )\n",
"print(\"'or' requires at least element to be True:\" , ( a * 2 > 10 ) or ( a > 0 ) )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Micro-exercises** : compute the product of 348 and 157.2. Use a comparison operator to check if the result is larger than 230 square (`230**2`)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
\n",
"\n",
"## Object types: container types\n",
"These types are object that contain other objects:\n",
"* `str`: string - text\n",
"* `list`: \"mutable\" list of python object\n",
"* `tuple`: \"immutable\" list of python object\n",
"* `dict`: dictionnary associating 'key' to 'value'\n",
"\n",
"They all have a dedicated `[]` operator that lets user access one - or several - of the object they contain. \n",
"In addition, the number of objects a container has (its length) can be accessed using the `len()` function. \n",
"**Important:** in python (unlike e.g. in R), indexing is zero-based. This means that the first element of an container type object is accessed with `object[0]`, and not `object[1]`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Strings\n",
"* In python, the `string` type is a sequences of characters that can be used to represent text of any length.\n",
"* Strings are represented surrounded by single `'` or double `\"` quotes. One can also use triple quotes `\"\"\"` to make a multi-line string."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Both single and double quotes can be used to define a string.\n",
"gene_seq = \"ATGCGACTGATCGATCGATCGATCGATGATCGATCGATCGATGCTAGCTAC\"\n",
"name = 'Sir Lancelot of Camelot'\n",
"\n",
"# Triple quotes can be used to define multi-line strings.\n",
"long_string = \"\"\"Let me tell you something, my lad. \n",
"When you’re walking home tonight and some great \n",
"homicidal maniac comes after you with a bunch \n",
"of loganberries, don’t come crying to me!\\n\"\"\"\n",
"print(long_string)\n",
"\n",
"# Special characters are possible.\n",
"my_quote = \"\"\"Gracieux : « aimez-vous à ce point les oiseaux\n",
"que paternellement vous vous préoccupâtes\n",
"de tendre ce perchoir à leurs petites pattes ? »\"\"\"\n",
"\n",
"# We also commonly use special characters, such as:\n",
"print('a\\tb') # \\t : tabulation\n",
"print('a\\nb') # \\n : newline\n",
"\n",
"# We can use the len() function to know the length of a string:\n",
"print(\"The length of the string in the 'name' variable is:\", len(name))\n",
"\n",
"# NB: strings can be added together and multiplied by an integer:\n",
"print( 'dead' + 'parrot' ) \n",
"print( 'spam' * 5 ) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The different letters of a string are accessed using the **`[]` operator**, with the index of the desired element. \n",
"Remember that in python, the index of the first element is `[0]`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"my_string = \"And now, something completely different.\"\n",
"print(\"The first element of this string is:\", my_string[0] ) # 0 is the index of the first element of the string\n",
"print(\"The 5th element of this string is:\", my_string[4] ) # 5th element of the string\n",
"print(\"The last element of this string is:\", my_string[-1] ) # -1 is the index of the last element of the string"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Indices can also be used to retrieve several element at once: this is called a **slice operation** or **slicing**."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(my_string[0:5]) # slice operation: get all elements from index 0 (included) to index 5 (excluded)\n",
"print(my_string[:5]) # this implicitely slices from the beginning of the string up to (but not included) index 5.\n",
"print(my_string[5:]) # this implicitely slices until the end of the string"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Micro exercise** : create a `str` variable containing your name. Extract the last 3 letters from it using slicing."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
\n",
"\n",
"### Lists and tuples\n",
"Lists and tuples are containers that can contain any type of element. \n",
"* Lists are declared by surrounding a comma separated list of objects with `[]`. \n",
"* Tuples are declared similarly, but using `()`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"myList = [ 1 , 2 , 3 , 5 , 5.2 , 6.99 ]\n",
"myTuple = ( 'a' , 4.2 , 5 ) # a list/tuple is not limited to a single type"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `[]` operator works in much the same way than with strings:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(myTuple[0])\n",
"print(myList[2:])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A `tuple` is **_immutable_** : its length is fixed and its elements cannot be changed.\n",
"\n",
"By comparison, a `list` is **_mutable_** : it can be extended, reduced, and its elements can be changed. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Changing an element in a list\n",
"myList[3] = \"Spam\"\n",
"print(myList[3])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"# Trying the same with a tuple raises an error:\n",
"myTuple[3] = \"Spam\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Remember the `help()` function ? Let's use it to gain a better undertsanding of the lists :"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"help(list)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"That's a lot of information... let's go through it! \n",
"The help page first defines the object `Built-in mutable sequence.`, then it describes the behaviour of `list()` if no argument is given (creates an empty list). \n",
"\n",
"Then, it says `Methods defined here:`. **methods** are functions that are attached to a type to enable some basic manipulation of objects of that type. \n",
"Methods are called using the syntax `object.method(...)`\n",
"\n",
"Let's focus on two of them :\n",
" * `append(self, object, /) `: this method adds an object (given as argument) at the end of the list.\n",
" * `insert(self, index, object, /)` : this method inserts an object (given as 2nd argument) at before the index given as the 1st argument.\n",
" \n",
"Let's try that:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"list before:\", myList)\n",
"\n",
"# Calling the \"append()\" method of myList to add an element at the end of it.\n",
"myList.append(\"ham\") \n",
"print(\"list after append:\", myList)\n",
"\n",
"# Calling the method insert of myList to add an element in second position. \n",
"# Remember that python indices start with 0, so inserting before position 1 puts the new object in second position in myList.\n",
"myList.insert(1 , \"beans\") \n",
"print(\"list after insert:\", myList)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Methods are an important part of python. Before you start writing your own code to manipulate an object, **always** check if the object already has a method that does exactly (or nearly) what you want.\n",
"This will save you a lot of time and grief."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### From list to string, and back again ...\n",
"\n",
"String variable can be converted to list using the `list()` function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"myString = \"Drop your panties Sir William, I cannot wait till lunchtime.\"\n",
"myList = list(myString)\n",
"print(myList)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The default behavior is that each letter of the string becomes an element in the list.\n",
"\n",
"Often we prefer to create a list that contains each word of the string. For this we use the `split()` method of string :"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"myWords = myString.split()\n",
"print(myWords)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `split()` method is very useful when reading formatted text files. \n",
"It can accepts an optional `sep` argument that allows separation of fields using another character (look up `help(str.split)` for details)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To convert a list to a string, use the `join` method can be used (which may be seen as the converse from split).\n",
"Somehow counter-intuitively, the `join` method applies to strings, and takes a list as argument:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Here, the separator calls the join method which accepts the list \"myWords\" as argument.\n",
"myString = \" \".join(myWords) \n",
"print(myString)\n",
"\n",
"# One can use a more exotic separator.\n",
"myString = \"_SEP_\".join(myWords) \n",
"print(myString)\n",
"\n",
"# TIP: use an empty separator to just join letters.\n",
"myString = \"\".join(['to','ba','c','co','ni','st']) \n",
"print(myString)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Bonus**: lists can be concatenated with the `+` operator, extended with `+=` (addition assignment) and \"multiplied\" with `*`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Crate a new list by appending two lists.\n",
"list_one = [ ',' , 1159 ]\n",
"list_two = list_one + [10.1, '45', 7] \n",
"print(list_two)\n",
"\n",
"# Extend a list with the += operator\n",
"# BTW, this could be written with the += operator:\n",
"# list_one += [10.1,'45',7] \n",
"\n",
"# As well as multiplication\n",
"menu = ['spam','eggs'] * 3 \n",
"print(menu)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Micro exercise** : create a list with all integers from 0 to 3 in it. Add two numbers at the end of the list. Use a slicing operation to select the fourth element in the list."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
\n",
"\n",
"### Dictionnaries\n",
"Dictionnaries, or `dict`, are containers that associate a **key** to a **value**, just like a real world dictionnary associates a word to its definition.\n",
"* Dictionaries are instantiated with the `{key:value}` or `dict()` syntax.\n",
"* **keys** must be unique in the dictionnary.\n",
"* **values** can appear as many time as desired in the dictionnary.\n",
"* the `[]` operator is used to select objects from the dictionnary, but using their key instead of their index.\n",
"* Unlike **Lists** or **Tuples**, **Dict** are unordered collections: they do not record element position or order of insertion. Therefore values cannot be retrieved by index position. \n",
" E.g. `test_dict[0]` is not a valid syntax (and will raise a `keyError`), unless there is a key value of \"0\" in the dict."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"student_age = dict() # this is one way to initiate a dictionnary\n",
"student_age = { 'Anne' : 26 , 'Viktor' : 31 } # this is another way to initiate a dictionnary, directly with data in\n",
"\n",
"# Adding key:value pairs to an existing dictionary is as easy as:\n",
"student_age['Eleonore'] = 5\n",
"print('dictionnary:', student_age)\n",
"\n",
"# Modifying the value associated to a key is equally easy:\n",
"student_age['Eleonore'] = 25\n",
"print('dictionnary:',student_age)\n",
"\n",
"# We are not restricted to a particular type for keys, nor for values. We can e.g. make dict of lists or dict of dict.\n",
"student_age[0] = 'zero' \n",
"student_age['group_1'] = [23, 25, 28] \n",
"student_age['group_2'] = {'bob':26, 'alice':27}\n",
"print('dictionnary:',student_age)\n",
"\n",
"# Removing objects from the dictionnary is done with the pop() method, look at the help for more details.\n",
"student_age.pop('Anne') \n",
"print('dictionnary:',student_age)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
\n",
"\n",
"## Exercises: 1.1 - 1.7"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
\n",
"\n",
"We recommend you have a look at the `Mutable_vs_immutable.ipynb` notebook to gain a better understanding of the difference between some the objects presented here.\n",
"This is an important notation that newcomers to Python need to be aware of, which otherwise can lead to serious bugs in our codes."
]
}
],
"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.7.4"
}
},
"nbformat": 4,
"nbformat_minor": 4
}