<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 <p><font size="6"><b>Python the essentials
Step1:  Python is a calculator
Step2:  also logical operators
Step3:  Variable assignment
Step4:  More information on print format
Step5:  <div class="alert alert-warning">
    <b>R comparison
Step6:  Loading with defined short name (community agreement)
Step10:  Loading functions from any file/module/package
Step11:  <div class="alert alert-info">
    <b>REMEMBER</b>
Step12:  integers
Step13:  booleans
Step14:  <div class="alert alert-warning">
    <b>R comparison
Step15:  Containers
Strings
Step16:  A string is a collection of characters...
Step17:  Lists
A list can contain mixed data types (character, float, int, other lists,...)
Step18:  <div class="alert alert-info">
    <b>REMEMBER</b>
Step19:  ADVANCED users area
Step20:  list comprehensions are basically a short-handed version of a for-loop inside a list. Hence, the previous action is similar to
Step21:  Another example checks the methods available for the list data type
Step22:  <div class="alert alert-success">
    <b>EXERCISE</b>
Step23:  <div class="alert alert-success">
    <b>EXERCISE</b>
Step24:  <div class="alert alert-warning">
    <b>R comparison
Step25:  <div class="alert alert-warning">
    <b>R comparison
Step26:  <div class="alert alert-info">
    <b>REMEMBER</b>
Step27:  Accessing container values
Step28:  <div class="alert alert-info">
    <b>REMEMBER</b>
Step29:  Select from...till
Step30:  Select, counting backward
Step31:  <div class="alert alert-warning">
    <b>R comparison
Step32:  From the first element until a given index
Step33:  Dictionaries
Step34:  Tuples
Step35:  <div class="alert alert-info">
    <b>REMEMBER</b>
Step36:  Control flows (optional)
for-loop
Step37:  <div class="alert alert-danger">
**Indentation** is VERY IMPORTANT in Python. Note that the second line in the example above is indented</li>
</div>
Step38:  <div class="alert alert-success">
    <b>EXERCISE</b>
Step39:  <div class="alert alert-info">
    <b>REMEMBER</b>
Step40:  if statement
Step41:  Functions
We've been using functions the whole time...
Step42:  <div class="alert alert-danger">
    It is all about calling a **method/function** on an **object**!
</div>
Step44:  <div class="alert alert-info">
    <b>REMEMBER</b>
Step45:  Setup of a function
Step46:  <div class="alert alert-success">
    <b>EXERCISE</b>
Step47:  Anonymous functions (lambda)
<ASSISTANT_TASK:>
Python Code:
print("Hello INBO_course!") # python 3(!)
Explanation: <p><font size="6"><b>Python the essentials: A minimal introduction</b></font></p>
Introduction to GIS scripting
May, 2017
© 2017, Stijn Van Hoey (&#115;&#116;&#105;&#106;&#110;&#118;&#97;&#110;&#104;&#111;&#101;&#121;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;). Licensed under CC BY 4.0 Creative Commons
First steps
the obligatory...
End of explanation
4*5
3**2
(3 + 4)/2, 3 + 4/2, 
21//5, 21%5  # floor division, modulo
Explanation: Python is a calculator
End of explanation
3 > 4, 3 != 4, 3 == 4
Explanation: also logical operators:
End of explanation
my_variable_name = 'DS_course'
my_variable_name
name, age = 'John', 30
print('The age of {} is {:d}'.format(name, age))
Explanation: Variable assignment
End of explanation
import os
Explanation: More information on print format: https://pyformat.info/
<div class="alert alert-info">
    <b>REMEMBER</b>:<br><br>
    <li>Use relevant variable names, e.g. `name` instead of `n`
    <li>Keep variable names lowercase, with underscore for clarity, e.g. `darwin_core` instead of `DarwinCore`
</div>
Loading functionalities
End of explanation
os.listdir()
Explanation: <div class="alert alert-warning">
    <b>R comparison:</b><br>
    <p>You would <b>load</b> a <b>library</b> (`library("ggplot2")`) instead of <b>importing</b> a package</p>
</div>
End of explanation
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Loading with defined short name (community agreement)
End of explanation
%%file rehears1.py  
#this writes a file in your directory, check it(!)
"A demo module."
def print_it():
    Dummy function to print the string it
    print('it')
import rehears1
rehears1.print_it()
%%file rehears2.py  
#this writes a file in your directory, check it(!)
"A demo module."
def print_it():
    Dummy function to print the string it
    print('it')
def print_custom(my_input):
    Dummy function to print the string that
    print(my_input)
from rehears2 import print_it, print_custom
print_custom('DS_course')
Explanation: Loading functions from any file/module/package:
End of explanation
a_float = 5.
type(a_float)
Explanation: <div class="alert alert-info">
    <b>REMEMBER</b>:<br><br>
Importing **packages** is always the first thing you do in python, since it offers the functionalities to work with!
</div>
Different options are available:
<span style="color:green">import <i>package-name</i></span> <br>importing all functionalities as such
<span style="color:green">from <i>package-name</i> import <i>specific function</i></span><br>importing a specific function or subset of the package
<span style="color:green">import <i>package-name</i> as <i>short-package-name</i></span><br>Very good way to keep a good insight in where you use what package
<div class="alert alert-danger">
    <b>DON'T</b>: `from os import *`. Just don't!
</div>
Datatypes
Numerical
floats
End of explanation
an_integer = 4
type(an_integer)
Explanation: integers
End of explanation
a_boolean = True
a_boolean
type(a_boolean)
3 > 4 # results in boolean
Explanation: booleans
End of explanation
print(False) # test yourself with FALSE
Explanation: <div class="alert alert-warning">
    <b>R comparison:</b><br>
    <p>Booleans are written as <b>False</b> or <b>True</b>, NOT as <b>FALSE/TRUE</b></p>
</div>
End of explanation
a_string = "abcde"
a_string
Explanation: Containers
Strings
End of explanation
a_string.capitalize(), a_string.upper(), a_string.endswith('f') # Check the other available methods for a_string yourself!
a_string.upper().replace('B', 'A')
a_string + a_string
a_string * 5
Explanation: A string is a collection of characters...
End of explanation
a_list = [1, 'a', 3, 4]
a_list
another_list = [1, 'a', 8.2, 4, ['z', 'y']]
another_list
a_list.append(8.2)
a_list
a_list.reverse()
a_list
Explanation: Lists
A list can contain mixed data types (character, float, int, other lists,...)
End of explanation
a_list + ['b', 5]
Explanation: <div class="alert alert-info">
    <b>REMEMBER</b>:<br><br>
    The list is updated <b>in-place</b>; a_list.reverse() does not return anything, it updates the list
</div>
End of explanation
[el*2 for el in a_list]  # list comprehensions...a short for-loop
Explanation: ADVANCED users area: list comprehensions
End of explanation
new_list = []
for element in a_list:
    new_list.append(element*2)
print(new_list)
Explanation: list comprehensions are basically a short-handed version of a for-loop inside a list. Hence, the previous action is similar to:
End of explanation
[el for el in dir(list) if not el[0] == '_']
Explanation: Another example checks the methods available for the list data type:
End of explanation
# %load ../notebooks/_solutions/01-python-introduction75.py
Explanation: <div class="alert alert-success">
    <b>EXERCISE</b>: 
<ul>
    <li>Rewrite the previous list comprehension by using a builtin string method to test if the element starts with an underscore</li>
</ul>
</div>
End of explanation
sentence = "the quick brown fox jumps over the lazy dog"
# %load ../notebooks/_solutions/01-python-introduction82.py
Explanation: <div class="alert alert-success">
    <b>EXERCISE</b>: 
<ul>
    <li>Given the sentence `the quick brown fox jumps over the lazy dog`, split the sentence in words and put all the word-lengths in a list.</li>
</ul>
</div>
End of explanation
a_dict = {'a': 1, 'b': 2}
a_dict['c'] = 3
a_dict['a'] = 5
a_dict
a_dict.keys(), a_dict.values(), a_dict.items()
an_empty_dic = dict() # or just {}
an_empty_dic
example_dict = {"timeseries": [2, 5, 3], 
                "parameter": 21.3,
                "scenario": "a"}
example_dict
Explanation: <div class="alert alert-warning">
    <b>R comparison:</b><br>
    <p>R also has lists as data type, e.g. `list(c(2, 5, 3), 21.3, "a")`</p>
</div>
Dictionary
A dictionary is basically an efficient table that maps keys to values. It is an unordered container
It can be used to conveniently store and retrieve values associated with a name
End of explanation
a_tuple = (1, 2, 4)
Explanation: <div class="alert alert-warning">
    <b>R comparison:</b><br>
    <p>R also has a dictionary like data type, e.g. </p>
</div>
```R
example_dict <- list(c(2,5,3),21.3,"a")
names(example_dict) <- c("timeseries", "parameter", "scenario")
example_dict
$timeseries
[1] 2 5 3
$parameter
[1] 21.3
$scenario
[1] "a"
```
Tuple
End of explanation
collect = a_list, a_dict
type(collect)
serie_of_numbers = 3, 4, 5
# Using tuples on the left-hand side of assignment allows you to extract fields
a, b, c = serie_of_numbers
print(c, b, a)
Explanation: <div class="alert alert-info">
    <b>REMEMBER</b>:<br><br>
    The type of brackets - (), [], {} - to use depends from the data type you want to create!
    <li> [] -> list
    <li> () -> tuple
    <li> {} -> dictionary
</div>
End of explanation
grades = [88, 72, 93, 94]
from IPython.display import SVG, display
display(SVG("../img/slicing-indexing.svg"))
grades[2]
Explanation: Accessing container values
End of explanation
from IPython.display import SVG, display
display(SVG("../img/slicing-slicing.svg"))
grades[1:3]
a_list = [1, 'a', 8.2, 4]
a_list[0], a_list[2]
Explanation: <div class="alert alert-info">
    <b>REMEMBER</b>: 
    <ul>
        <li> Python starts counting from <b>0</b> !
    </ul>
</div>
End of explanation
a_string = "abcde"
a_string
a_string[2:4]
Explanation: Select from...till
End of explanation
a_list[-2]
Explanation: Select, counting backward:
End of explanation
a_list = [0, 1, 2, 3]
Explanation: <div class="alert alert-warning">
    <b>R comparison:</b><br>
    <p>The `-` symbol in R has a completely different meaning: `NOT`</p>
</div>
```R
test <- c(1, 2, 3, 4, 5, 6)
test[-2]
[1] 1 3 4 5 6
```
End of explanation
a_list[:3]
a_list[::2]
Explanation: From the first element until a given index:
End of explanation
a_dict = {'a': 1, 'b': 2}
a_dict['a']
Explanation: Dictionaries
End of explanation
a_tuple = (1, 2, 4)
a_tuple[1]
Explanation: Tuples
End of explanation
a_list
a_list[2] = 10 # element 2 changed -- mutable
a_list
a_tuple[1] = 10 # cfr. a_string -- immutable
a_string[3] = 'q'
Explanation: <div class="alert alert-info">
    <b>REMEMBER</b>: 
    <ul>
        <li> [] for accessing elements
    </ul>
</div>
Note that L[start:stop] contains the elements with indices i such as start &lt;= i &lt; stop
(i ranging from start to stop-1). Therefore, L[start:stop] has (stop-start) elements.
Slicing syntax: L[start:stop:stride]
all slicing parameters are optional
Assigning new values to items -> mutable vs immutable
End of explanation
for i in [1, 2, 3, 4]:
    print(i)
Explanation: Control flows (optional)
for-loop
End of explanation
for i in a_list: # anything that is a collection/container can be looped
    print(i)
Explanation: <div class="alert alert-danger">
**Indentation** is VERY IMPORTANT in Python. Note that the second line in the example above is indented</li>
</div>
End of explanation
# %load ../notebooks/_solutions/01-python-introduction172.py
for i in a_dict: # items, keys, values
    print(i)
for j, key in enumerate(a_dict.keys()):
    print(j, key)
Explanation: <div class="alert alert-success">
    <b>EXERCISE</b>: 
<ul>
    <li>Loop through the characters of the string `Hello DS` and print each character separately within the loop</li>
</ul>
</div>
End of explanation
b = 7
while b < 10:
    b+=1
    print(b)
Explanation: <div class="alert alert-info">
    <b>REMEMBER</b>: <br><br>
    When needing a iterator to count, just use `enumerate`. you mostly do not need i = 0 for... i = i +1.  
    <br>
    Check [itertools](http://pymotw.com/2/itertools/) as well...
</div>
while
End of explanation
if 'a' in a_dict:
    print('a is in!')
if 3 > 4:
    print('This is valid')
testvalue = False  # 0, 1, None, False, 4 > 3
if testvalue:
    print('valid')
else:
    raise Exception("Not valid!")
myvalue = 3
if isinstance(myvalue, str):
    print('this is a string')
elif isinstance(myvalue, float):
    print('this is a float')
elif isinstance(myvalue, list):
    print('this is a list')
else:
    print('no idea actually')
Explanation: if statement
End of explanation
len(a_list)
Explanation: Functions
We've been using functions the whole time...
End of explanation
a_list.reverse()
a_list
Explanation: <div class="alert alert-danger">
    It is all about calling a **method/function** on an **object**!
</div>
End of explanation
def custom_sum(a, b, verbose=False):
    custom summation function
    
    Parameters
    ----------
    a : number
        first number to sum
    b : number
        second number to sum   
    verbose: boolean
        require additional information (True) or not (False)
    
    Returns
    -------
    my_sum : number
        sum of the provided two input elements
    
    
    if verbose:
        print('print a lot of information to the user')
        
    my_sum = a + b    
    
    return my_sum
Explanation: <div class="alert alert-info">
    <b>REMEMBER</b>:<br><br>
    Getting an overview of the available methods on the variable (i.e. object):
    <img src="../img/tabbutton.jpg"></img>
</div>
Defining a function:
End of explanation
custom_sum(2, 3, verbose=False)  # [3], '4'
Explanation: Setup of a function:
definition starts with def
function body is indented
return keyword precedes returned value
<div class="alert alert-danger">
**Indentation** is VERY IMPORTANT in Python. Note that the second line in the example above is indented</li>
</div>
End of explanation
def f1():
    print('this is function 1 speaking...')
def f2():
    print('this is function 2 speaking...')
def function_of_functions(inputfunction):
    return inputfunction()
function_of_functions(f1)
Explanation: <div class="alert alert-success">
    <b>EXERCISE</b>: 
<ul>
    <li>Try **SHIFT-TAB** combination to read your own documentation!</li>
</ul>
</div>
<div class="alert alert-info">
    <b>REMEMBER</b>:<br><br>
    () for calling functions!
</div>
ADVANCED users area:
Functions are objects as well... (!)
End of explanation
add_two = (lambda x: x + 2)
add_two(10)
Explanation: Anonymous functions (lambda)
End of explanation
<END_TASK>