Skip to content
Snippets Groups Projects
Commit f824f400 authored by nyfelix's avatar nyfelix
Browse files

unit 4 work in process

parent d650ef89
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## For the Geeks: Lambdas
* Sometimes our code expects values that must be calculate first, for a function parameter.
* In Python, we can do this wiht Lambda functions.
* Lambdas are functions that are declared right where they are used and only persist for the time beeing executed (generally such functions are also called annoynomous functions, because they don't have a name).
* Like functions, Lambdas are as objects, and they can be passed to as a function argument.
Syntay of a Lambda is:
```
lambda arguments : expression
```
%% Cell type:code id: tags:
``` python
x = lambda a : a + 10 # a is the argument, a + 10 is the expression, the result is assigned to x
print(x(5))
```
%% Output
15
%% Cell type:markdown id: tags:
Exampele:
%% Cell type:code id: tags:
``` python
def double(x):
return x * 2
map(double, [1,2,3,4])
```
%% Output
<map at 0x107955ed0>
%% Cell type:markdown id: tags:
Can be forumulated as:
%% Cell type:code id: tags:
``` python
map(lambda x: x * 2, [1,2,3,4])
```
%% Output
<map at 0x107954f40>
%% Cell type:markdown id: tags:
Which seem s a lot more elegant to me
This diff is collapsed.
%% Cell type:markdown id: tags:
# Agenda
* Python Syntax
* Variables & Data Types
* Operators
* Decisions
* Loops
* Lists
* Iterations
%% Cell type:markdown id: tags:
# Python Syntax
%% Cell type:markdown id: tags:
## Structure of the Code
* Basically, Python code executes from top top bottom
* Every programming language organizes code in code blocks (statements that belong together)
* Indentation in Python is very important (it's mandatory not optional)
* Every code block (subcode) must be indented
* Unlike other languages, code blocks do not require brackets {}
* The number of spaces is up to you you, the most common use is four, but it has to be at least one.
%% Cell type:code id: tags:
``` python
if 5 > 2:
print("Five is greater than two!")
print("This is a second statement.")
else:
print("The world is a disk!")
```
%% Cell type:code id: tags:
``` python
if 5 > 2:
print("Five is greater than two!")
```
%% Output
Cell In[4], line 2
print("Five is greater than two!")
^
IndentationError: expected an indented block
%% Cell type:markdown id: tags:
## Important Keywords (must not be used as names)
* As with every programming language, there are some keywords that belong to the language and must not be used for names
* Some popular ones are: True, False, None, def, class, break, return
The code below prints the full list
%% Cell type:code id: tags:
``` python
import keyword
print(keyword.kwlist)
```
%% Cell type:markdown id: tags:
# Comments
* Python has commenting capabilities for the purpose of in-code documentation.
* Comments start with a #, and Python will ignore them:
%% Cell type:code id: tags:
``` python
# This is a comment
print("Hello, World!")
```
%% Cell type:markdown id: tags:
* Comments can be placed at the end of a line, and Python will ignore the rest of the line
%% Cell type:code id: tags:
``` python
print("Hello, World!") #This is a comment
```
%% Cell type:markdown id: tags:
# Variables and Data Types
%% Cell type:markdown id: tags:
## Introducing a Variable in Python
* Variables are an essential concept to store data.
* Python has no command for declaring a variable.
* A variable is automatically created when you first assign a value to it.
* In Python, variables are not declared with any particular type.
* To output the value of a variable, we use the `print()` command.
Let's see some examples
%% Cell type:code id: tags:
``` python
x = 10
print(x)
y = "This is a string"
print(y)
```
%% Output
10
This is a string
%% Cell type:markdown id: tags:
## Naming Conventions
* It is very important to choose meaningful names for variables
* This will make your code better readable to others as well
* You need fewer comments to explain your code
* These are the most important rules and conventions:
* PEP 8 Style Guide for Python Code https://peps.python.org/pep-0008/#naming-conventions
* A good summary can be found here: https://medium.com/@rowainaabdelnasser/python-naming-conventions-10-essential-guidelines-for-clean-and-readable-code-fe80d2057bc9
%% Cell type:markdown id: tags:
## Most Important Naming Conventions
* Names **never start with a number**
* We **don't use special characters** in names (ASCII compatiblity)
* **Variable and Function Names**: Use `snake_case` (all lowercase letters with words separated by underscores).
* **Constants**: Use `ALL_CAPS` with words separated by underscores. Constants are usually defined at the top of a module.
* **Boolean Variables**: Should be named to sound like a yes/no question or statement, often starting with `is`, `has`, `can`, or `should`. E.g., `is_approved`
* **Class Names**: Use `PascalCase` (each word starts with an uppercase letter, no underscores).
%% Cell type:markdown id: tags:
## Data Types I
* Variables store values, and these values are of a particular type
* Different types exhibit different behavior
* Adding two integers will result in the arithmetic sum
* Adding two strings will result in a string containing both substrings
* different data types have different functions available
%% Cell type:code id: tags:
``` python
x = 4
y = 5
z = x + y
print(z)
x = "Text"
y = " more text"
z = x + y
print(z)
```
%% Output
9
Text more text
%% Cell type:markdown id: tags:
## Data Types II
These are the built-in data types of Python
| Type Category | Data Types |
|---------------------|------------------------------------|
| Text Type | 'str' |
| Numeric Types | 'int', 'float', 'complex' |
| Sequence Types | 'list', 'tuple', 'range' |
| Mapping Type | 'dict' |
| Set Types | 'set', 'frozenset' |
| Boolean Type | 'bool' |
| Binary Types | 'bytes', 'bytearray', 'memoryview' |
| None Type | 'NoneType' |
Some of these we will use soon, while others you will learn throughout the semester.
%% Cell type:markdown id: tags:
## Boolean Data Type
* Boolean: `bool` has only two possible values: `True` or `False`
* In programming you often need to know if an expression is `True` or `False`.
* E.g. comparing values always returns boolean result
* Technically `False` correspons to the value of 0, any other number is considerd `True` (will be important for casting to bool)
%% Cell type:code id: tags:
``` python
10 > 9
```
%% Output
True
%% Cell type:markdown id: tags:
* Boolian variables / expressions are important for decisions
%% Cell type:code id: tags:
``` python
is_true = 10 > 9
if (is_true):
print("10 is greater than 9")
```
%% Output
10 is greater than 9
%% Cell type:markdown id: tags:
## Number Data Type
Python konws 3 numeric data types:
| Type | Explanation | Example |
| --------- | ----------------------------------------------------------------------------------------------------- | ---------------------- |
| `int` | A whole number, positive or negative, without decimals, of unlimited length. | 3, 88, -12837654 |
| `float` | Float, or "floating point number" is a number, positive or negative, containing one or more decimals. | 7.5, 1212.875620, 35e3 |
| `complex` | Complex numbers are written with a "j" as the imaginary part: | 3+5j |
%% Cell type:code id: tags:
``` python
x = 10 # int
y = 10.0 # float needs a .0 to be a float
z = 2 + 3j # complex
```
%% Cell type:markdown id: tags:
Float can also be scientific numbers with an "e" to indicate the power of 10
%% Cell type:code id: tags:
``` python
x = 35e3
print(x)
```
%% Output
35000.0
%% Cell type:markdown id: tags:
## Text Data Types I
* Besides numbers, we often want to process text in our programms
* Python's built-in data type to do so is: `str`
* Strings in python are surrounded by either single quotation marks, or double quotation marks. `'hello'` can be used as well as `"hello"`.
%% Cell type:code id: tags:
``` python
my_name = "John"
my_name = 'John'
```
%% Cell type:markdown id: tags:
* Special characters must be "escaped" with a I \ (\n = return, \t = tabulator)
* " is allowed inside singel quotes, ' is allowed inside double quotes
%% Cell type:code id: tags:
``` python
my_text = "this is 'ok' a double-quote needs an escape: \" to work"
my_text = 'here we can use "" but \' must be escaped'
print("this is a \nreturn")
```
%% Output
this is a
return
%% Cell type:markdown id: tags:
## Text Data Types II
* Strings can be concatibated
%% Cell type:code id: tags:
``` python
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
```
%% Output
John Doe
%% Cell type:markdown id: tags:
* Strings have various functions, that can be accessed
%% Cell type:code id: tags:
``` python
print(full_name.upper())
print(full_name.count("o"))
```
%% Output
JOHN DOE
2
%% Cell type:markdown id: tags:
## Type Casting
* Sometimes you want to explicitly change the data type of a variable
* This process is called casting or type casting
* In Python we do have functions to do this
* Casting functions are available for all built-in datatypes, where the function name equals the type name
Here are the most important ones:
%% Cell type:code id: tags:
``` python
a = str(3) # Change an int value to a string
print(type(a))
b = int(3.7) # Change a float value to an int
print(b)
c = float(3) # Change an int value to a float
print(c)
c = int("3") # Change a string value to a int
print(c)
```
%% Output
<class 'str'>
3
3.0
3
%% Cell type:markdown id: tags:
## For the Geeks: Background Knowledge I
* In Python, everything is an Object (an instance of a complex data type with functions and behavior)
* More precise, a variable points to an instance of an object
* The `is` operator checks whether two variables point to the same object in memory, not just if they have the same value.
%% Cell type:code id: tags:
``` python
x = 10.0
id(x)
```
%% Output
4537738384
%% Cell type:code id: tags:
``` python
y = x
id(y)
```
%% Output
4537738384
%% Cell type:code id: tags:
``` python
x is y
```
%% Cell type:code id: tags:
``` python
x is 10.0
```
%% Cell type:markdown id: tags:
## For the Geeks: Background Knowledge II
* However, a new assignment creates a new object.
%% Cell type:code id: tags:
``` python
y = 20.0
id(y)
```
%% Output
4455295664
%% Cell type:markdown id: tags:
* Thus, variables can be reassigned to a different type at runtime (variable remains a pointer, but to a different address/object).
%% Cell type:code id: tags:
``` python
x = 10
print(type(x))
x = "This is a string"
print(type(x))
```
%% Output
<class 'int'>
<class 'str'>
%% Cell type:markdown id: tags:
# Operators
%% Cell type:markdown id: tags:
## Types of Operators
* To work (compare, add, etc.) with variables, we need operators
* Python categorizes operators into the following groups:
* Arithmetic operators
* Assignment operators
* Comparison operators
* Logical operators
* *Identity operators*
* *Membership operators*
* *Bitwise operators*
Reference: https://www.w3schools.com/python/python_operators.asp
%% Cell type:markdown id: tags:
## Arithmetic Operators
We need arithmetic operators to calculate.
| Operator | Name | Example |
|----------|----------------|----------|
| `+` | Addition | `x + y` |
| `-` | Subtraction | `x - y` |
| `*` | Multiplication | `x * y` |
| `/` | Division | `x / y` |
| `%` | Modulus | `x % y` |
| `**` | Exponentiation | `x ** y` |
| `//` | Floor division | `x // y` |
%% Cell type:code id: tags:
``` python
5**2
```
%% Output
25
%% Cell type:markdown id: tags:
## Assignment Operators
We need assignment operators to assign values to variables.
| Operator | Example | Same As |
|----------|---------|-------------|
| `=` | `x = 5` | `x = 5` |
| `+=` | `x += 3`| `x = x + 3` |
| `-=` | `x -= 3`| `x = x - 3` |
| `*=` | `x *= 3`| `x = x * 3` |
| `/=` | `x /= 3`| `x = x / 3` |
%% Cell type:code id: tags:
``` python
x = 5
x *=2
print(x)
```
%% Output
10
%% Cell type:markdown id: tags:
## Comparison Operators
Comparison operators are needed to make decisions.
The result of a comparison operator is always `true`or `false`.
| Operator | Name | Example |
|----------|-----------------------------|-----------|
| `==` | Equal | `x == y` |
| `!=` | Not equal | `x != y` |
| `>` | Greater than | `x > y` |
| `<` | Less than | `x < y` |
| `>=` | Greater than or equal to | `x >= y` |
| `<=` | Less than or equal to | `x <= y` |
%% Cell type:code id: tags:
``` python
4 == 2
```
%% Output
False
%% Cell type:code id: tags:
``` python
4 > 2
```
%% Output
True
%% Cell type:markdown id: tags:
## Logical Operators
Logical operators are important if a decision is more complex and needs to consider several comparisons.
The logical operators can only compare values of `True` (>0) or `False` (=0) and result in `True`or `False`.
Here's the table formatted in Markdown:
| Operator | Description | Example |
|----------|-----------------------------------------------|------------------------------- |
| `and` | Returns True if both statements are true | `x < 5 and x < 10` |
| `or` | Returns True if one of the statements is true | `x < 5 or x < 4` |
| `not` | Reverses the result; returns False if true | `not (x < 5 and x < 10)` |
%% Cell type:code id: tags:
``` python
x = 11
not (x > 5 and x < 10)
```
%% Output
True
%% Cell type:markdown id: tags:
# Control Structures
%% Cell type:markdown id: tags:
## Decisions
* One of the most common things you want to do when writing a computer program is to act upon decisions/conditions
* This is done using the 'if' statement, followed by a boolean expression, followed by a ':'
* If the statement is 'True' the code block below will be executed (indentation)
%% Cell type:code id: tags:
``` python
x = 9
if x > 5:
print("x is greater than 5")
```
%% Output
x is greater than 5
%% Cell type:markdown id: tags:
* Optionally, we can add zero or more `elif` parts, and the `else`
%% Cell type:code id: tags:
``` python
x = 3
if x > 5:
print("x is greater than 5")
elif x < 2:
print("x is less than 2")
else:
print("x between 2 and 5")
```
%% Output
x between 2 and 5
%% Cell type:markdown id: tags:
## Loops
* Another very common concept in programming is loops.
* We want to repeat an action until a certain condition becomes true.
* In Python, we use the `while` statement for loops:
%% Cell type:code id: tags:
``` python
a = 0
while a < 10:
print(a)
a += 2
```
%% Output
0
2
4
6
8
%% Cell type:markdown id: tags:
## Lists
* We have already learned about data types.
* Python has several types to manage a lists of data (This is one of Python's strengths)
* Python has several types to manage a lists of data (this is one of Python's strengths)
* Let's introduce the most common sequence type: `list`
* Lists are used to store multiple items in a single variable.
* A list is ordered, this means that each value has an exact position in the list.
* Lists are created using square brackets.
%% Cell type:code id: tags:
``` python
fruits = ["apple", "orange", "grape"]
```
%% Cell type:markdown id: tags:
* An element in a list can be accessed by the variable, followed by the index (position) in `[]``
* The first element has the index 0
%% Cell type:code id: tags:
``` python
apple = fruits[0]
print(fruits[1])
```
%% Output
orange
%% Cell type:markdown id: tags:
## Working with Lists
* A list object has various functions to query and modify the list.
Here are some examples of common list actions:
%% Cell type:code id: tags:
``` python
fruits = ["apple", "orange", "grape", "orange"]
fruits.append("banana") # add a new element to the end
print(fruits)
fruits.insert(1, "cherry") # add a new element at index 1
print(fruits)
fruits.pop(2) # remove element at position 2
print(fruits)
fruits.sort() # sort the list
same_fruits = fruits.copy() # returns a copy of the list
print(fruits)
```
%% Output
['apple', 'orange', 'grape', 'orange', 'banana']
['apple', 'cherry', 'orange', 'grape', 'orange', 'banana']
['apple', 'cherry', 'grape', 'orange', 'banana']
['apple', 'banana', 'cherry', 'grape', 'orange']
%% Cell type:markdown id: tags:
* Unlike arrays in other programming languages, Python's lists can store mixed data types
%% Cell type:code id: tags:
``` python
list1 = ["abc", 34, True, 40, "male"]
```
%% Cell type:markdown id: tags:
## Iterations I
* When working with lists, we often want to iterate through all elements of a list
* In Python we use the `for ... in ...:` statement for this
* The code block will be executed for each element in the list
* The variable before the in will be assigned the current element of the list.
* The behind the 'in' is the list being referenced.
%% Cell type:code id: tags:
``` python
fruits = ["apple", "orange", "grape", "banana"]
for fruit in fruits:
print(fruit)
```
%% Output
apple
orange
grape
banana
%% Cell type:markdown id: tags:
## Iterations II
* Sometimes we don't have a list, but want to iterated over a range of numbers, e.g. from 0 to 10
* In Python we have the `range()` function to create a list of arithmetic progressions
%% Cell type:code id: tags:
``` python
list = range(5) # Creates a list with 5 values, starting from 0
list = range(5, 10) # Creates a list with int from 5 to 9 (interval 5, 10)
list = range(0, 10, 3) # Creates a list auf values between 0 and 10 with increase of 3 very step
```
%% Cell type:markdown id: tags:
* We can use range() to build 'for' loops
%% Cell type:code id: tags:
``` python
for i in range(0, 8, 2): # in C++ this would be for (int i=0; y<10; i+=2)
print(i)
```
%% Output
0
2
4
6
%% Cell type:markdown id: tags:
## Breaking Loops
* Sometimes we want to break out of a loop to savee time
* In Python, we have two statements to do so, they work with `for` and `while` loops
* `break` jumps out of the complete loop and continues after the loop statement
* `continue` continues with the next iteration of the loop
%% Cell type:code id: tags:
``` python
for i in range(10):
if i == 1:
continue # go to the next loop, don't execute code below
if i == 4:
break # completely jump out of the loop
print(i)
print("This is the next line of code after the loop")
```
%% Output
0
2
3
This is the next line of code after the loop
......
%% Cell type:markdown id: tags:
# Agenda
* Adding structure to Python code
* Functions
* Namespaces
* Modules
%% Cell type:markdown id: tags:
# Code Structure
%% Cell type:markdown id: tags:
## Adding structure to Python code
* There are many good reasons why we want to organize our code and add structure to it
* Reuse : We don't want to do things twice
* Readability : structured code can be read like a language
* Maintainability : If we don't have a good structure in code, we can spend a lot time with searching
* In Python we have different concepts to give structure to our code:
* Functions
* Namespaces
* Modules
* Classes (we will come back to this great concept at the end of this course)
%% Cell type:markdown id: tags:
# Functions
%% Cell type:markdown id: tags:
## Usage of Functions
* Functions allow us to define a block of code that can be called from anywhere
* Functions accept *parameters* (arguments) as input into the code block
* Optionally, functions can *return* a value
* As soon as you repeat the same or similar sequence of code, consider writing a function
* Functions are called with the function name, followed by ()
* If the function accepts parameters, they are listed inside (), separated with comma
* If the function returns a value, it can be assigned to a variable
Here is an example:
%% Cell type:code id: tags:
``` python
my_number = max(3, 4, 2) # calling the function with 3 arguments and assigning the result to a variable
print(my_number) # also print is a function
```
%% Output
4
%% Cell type:markdown id: tags:
## Definition of Functions
* To define a function, we use the `def`keyord, followed by the function name
* After the function name we declare in () which parameters are allowed
* If we want to return a value, we can do this anywhere with the `return` statement, followed by the return value(s)
%% Cell type:code id: tags:
``` python
# Define a function that takes two arguments and returns the bigger one
def bigger_of_two(a, b):
if a > b:
return a
else:
return b
# Call the function with two arguments and print the result
print(bigger_of_two(4, 3))
```
%% Output
4
%% Cell type:markdown id: tags:
## Scope of Variables
* Variables that are first used in a function are only known inside this function
* However functions can access variables of the outer scope (e.g. global variables)
* Variables in the most outer scope are called "global variables"
* Variables in a closed inner scope are called "local variables"
%% Cell type:code id: tags:
``` python
x = 8
def some_function():
print("Value from outer scope:", x) # x is accessible from the inner scope
y = 3
print("Value from same scope:", y) # y is not accessible from the outer scope
some_function()ß
print("Value from inner scope:", y)
```
%% Output
Value from outer scope: 8
Value from same scope: 3
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[3], line 8
5 print("Value from same scope:", y) # y is not accessible from the outer scope
7 some_function()
----> 8 print("Value from inner scope:", y)
NameError: name 'y' is not defined
%% Cell type:markdown id: tags:
## Assigning multiple values
* in Python we can assign multiple values to multiple variables in one line
* Accordingly, we can write functions that return multiple values, which can be very handy
%% Cell type:code id: tags:
``` python
def get_min_max(list):
minimum = min(list)
maximum = max(list)
return minimum, maximum # returning multiple values
list_min, list_max = get_min_max([1, 2, 3, 4, 5]) # multiple assignment (first value goes to a, second to b)
print(list_min)
```
%% Cell type:markdown id: tags:
## More About Funtions in Python
* Default Parameter Value : You can define default values, in case the function is called without parameter
%% Cell type:code id: tags:
``` python
def default_argument(a, b, c=3): # default value for c
return a + b + c
print(default_argument(1, 2)) # c will be 3
```
%% Cell type:markdown id: tags:
* Arbitrary Arguments, *args : If you do not know how many arguments that will be passed into your function, add a * before the argument name
%% Cell type:code id: tags:
``` python
def arbitrary_argument(*args): # variable number of arguments
sum = 0
for a in args:
sum += a
return sum
print(arbitrary_argument(1, 2, 4, 6))
```
%% Cell type:markdown id: tags:
* There is more we can do with functions, but this is a good start.
%% Cell type:markdown id: tags:
## For the Geeks: Lambdas
* Sometimes our code expects value that must be calculate first
* With Lambda functions we can do this
%% Cell type:markdown id: tags:
# Modules
%% Cell type:markdown id: tags:
## Using Modules I
* One of the biggest advantages of Python is the incredible number of modules that are available
* Modules are pieces of code that exist somewhere else (typically in another file)
* Modules can be imported with the `` import module_name `` statement
* The module name can be any installed python module,
* or the name of file somewhere in your project (name without the '.py' ending)
* Functions of a module are accessible with the module name and the `` . `` operator
%% Cell type:code id: tags:
``` python
import math # importing a module
math.sqrt(16) # using a function from the module
```
%% Cell type:markdown id: tags:
## Using Modules II
* If a module can be organized in submodules by placing them in a folder or subfolder of your project
* The module name will then be `` module.submodule `` (according to the fodler structure)
* To access a function you will have to write something like `` module.submodule.function() ``
* In this case we want to create a shortcut.
* In Python this can be done with as `` as `` order: ``import folder.module as mod ``
%% Cell type:code id: tags:
``` python
import pandas.plotting as pdp # importing a submodule
pdp.lag_plot() # using a function from the submodule
```
%% Cell type:markdown id: tags:
## Installing Modules
* As mentioned earlier, Python has a vast variety of modules (currently about 570k registered packages)
* You can find the official registry here: https://pypi.org/
* Luckily we don't have to search and copy them from the internet
* Python has package management tool, called pip that helps us to install modules
```
pip install <module name>
pip install pandas
```
if you have several Python versions you may have to use the specifice pip command
```
pip3 install <module name>
```
%% Cell type:markdown id: tags:
## Crating a Module
* At some point your code will get bigger
* And also you might want to reuse your own code in other projects
* In this case it is a good idea to start organizing your code in modules
* Creating a modules is as easy as creating a new .py file
* Let's code a simple example.
%% Cell type:markdown id: tags:
# Namespaces
%% Cell type:markdown id: tags:
## Namespace Rules
<img style="float: right; padding-right: 50pt;" src="https://files.realpython.com/media/t.fd7bd78bbb47.png" width="300pt">
* Now that we know functions and modules, it's time to have a closer look at namespaces
* A namespaces the scope in which a name (variable, function, class, ...) is valid
* Names must be unique in their namespaces
* Python knows3 types of namespaces with the following rules:
1. Local: If you refer to x inside a function, then the interpreter first searches for it in the innermost scope that’s local to that function.
2. Enclosing: If x isn’t in the local scope but appears in a function that resides inside another function, then the interpreter searches in the enclosing function’s scope.
3. Global: If neither of the above searches is fruitful, then the interpreter looks in the global scope next.
4. Built-in: If it can’t find x anywhere else, then the interpreter tries the built-in scope.
%% Cell type:markdown id: tags:
## Working with Namespaces
* In Python functions, modules (and classes) act as enclosing and local namespaces
* You might have realized: modules automatically act as a namespace
* Their structure determine the scope of names
* Considering memory:
* Global variables remain in the RAM all time
* Local variables only use memory while the object defining the namespace exists
%% Cell type:code id: tags:
``` python
x = 1
def namespaces():
def subspaces():
z = 3
print(pow(3,2)) # access namespaces from the built-in scope
print(x) # access x from the global scope
print(y) # access y from the enclosing scope
print(z) # access z from the local scope
y = 2
subspaces()
print(y) # access y from the local scope
print(z) # z is not accessible from the outer scope (NameError)
namespaces()
```
%% Output
9
1
2
3
%% Cell type:markdown id: tags:
## For the Geeks
* Careful about redeclaration!
* While an enclosing variable x can be read in an inner namespaces, a new variable will be created at the moment you assign a value to this variable.
%% Cell type:code id: tags:
``` python
def namespaces():
def subspaces():
x = 2 # x is now a local variable
print(x)
x = 1 # x is a local variable of namespaces
subspaces()
print(x)
namespaces()
```
%% Output
2
1
......
%% Cell type:markdown id: tags:
# Extended Data Types
%% Cell type:markdown id: tags:
# Agenda
* Lists (repetition)
* Tuples
* Sets
* Dictionaries
%% Cell type:markdown id: tags:
## Introduction
* We already know lists
* Lists are only one of 4 built-in data types in Phython that store collections of data:
* Lists
* Tuples
* Sets
* Dictionaries
* Collections are used to store multiple items in a single variable.
* Working with collections is something that makes Python extremly powerful
%% Cell type:markdown id: tags:
## Recap of what we know about Lists
1. Lists are created with square brackets ```[ ]```
%% Cell type:code id: tags:
``` python
list = [1,2,5,3]
```
%% Cell type:markdown id: tags:
2. List items are ordered, changeable, and allow duplicate values
* Orders: Items have a defined order, and that order will not change unless we add or remove items
* Changable: We can change, add, and remove items in a list after it has been created
3. We access list items by thier index (the position in the list, starting with 0)
%% Cell type:code id: tags:
``` python
list = [1,2,3,3,2]
print(list[3])
```
%% Output
3
%% Cell type:markdown id: tags:
## Accessing List Items
Besides accessing list items with ```[index]``` Python offers some additional options:
1. Negative Indexing: ```[-1]``` refers to the last item, ```[-2]``` refers to the second last item etc.
%% Cell type:code id: tags:
``` python
my_list = ['a','b','c','d']
print(my_list[-1])
print(my_list[-2])
```
%% Output
d
c
%% Cell type:markdown id: tags:
2. Instead of selecting a single item we can also select a subset of the list with the schema ```start-index:end-index```
%% Cell type:code id: tags:
``` python
my_list = ['a','b','c','d']
print(my_list[1:3])
```
%% Output
['b', 'c']
%% Cell type:markdown id: tags:
## List Functions
We have already seen the most important list methods (functions). Here is a complete table:
| Method | Description |
| :-------- | :--------------------------------------------------------------------------- |
| append() | Adds an element at the end of the list |
| clear() | Removes all the elements from the list |
| copy() | Returns a copy of the list |
| count() | Returns the number of elements with the specified value |
| extend() | Add the elements of a list (or any iterable), to the end of the current list |
| index() | Returns the index of the first element with the specified value |
| insert() | Adds an element at the specified position |
| pop() | Removes the element at the specified position |
| remove() | Removes the item with the specified value |
| reverse() | Reverses the order of the list |
| sort() | Sorts the list |
See https://www.w3schools.com/python/python_lists_methods.asp for more details.
%% Cell type:markdown id: tags:
## Tuples
* A tuple is a collection which is ordered and **unchangeable**.
* Tuples are written with round brackets.
* Tuples are orded and allow duplicate values.
* Items of tuples are accessed exactly the same way as lists with ```[]```
%% Cell type:code id: tags:
``` python
my_tuple = ("mia", "mio", 1)
print(my_tuple[2])
```
%% Output
1
%% Cell type:markdown id: tags:
* Tuples only know the methods ```count()```and ```index()```
%% Cell type:markdown id: tags:
## Sets
* A set is a collection which is unordered, and unindexed and its itmes are unchangeable.
* Once a set is created, you cannot change its items, but you can add new items.
* Dublicate items will be treated as one item
* Like lists and tuples, sets can contain multiple data types
* You cannot access items in a set by referring to an index or a key (since they have no order)
* Sets are written with curly brackets.
%% Cell type:code id: tags:
``` python
my_set = {1, 5, 3, 1} # last value will be ignored
my_set.add(1) # will be ignored
for x in my_set:
print(x)
print(2 in my_set)
```
%% Output
1
3
5
False
%% Cell type:markdown id: tags:
* Sets are highly useful to efficiently remove duplicate values from a collection like a list and to perform common math operations like unions and intersections.
%% Cell type:markdown id: tags:
## Dictionaries
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment