Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • riccardo.caracciolo/pyeng-lectures
  • sandro.rufibach/pyeng-lectures
  • edu-public/python-for-engineers/pyeng-lectures
3 results
Show changes
Commits on Source (86)
Showing
with 81494 additions and 210 deletions
......@@ -31,3 +31,16 @@ Use the following command to convert lectures to static html presentations
```
jupyter nbconvert LECTURE.ipynb --to slides --post serve
```
To create a pdf of the slides use
```
jupyter nbconvert --to slides lecture.ipynb --post serve
```
Open browser and naivgate to URL
```
http://127.0.0.1:8000/lecture.slides.html?print-pdf
```
Command-P and save as PDF
[
{"sensor_id": "A1", "temperature": 23.5, "humidity": null, "pressure": 1013.2},
{"sensor_id": "B2", "temperature": null, "humidity": null, "pressure": 1008.1},
{"sensor_id": "C3", "temperature": 19.4, "humidity": null, "pressure": null},
{"sensor_id": "D4", "temperature": null, "humidity": null, "pressure": null},
{"sensor_id": "E5", "temperature": 22.4, "humidity": 0.8, "pressure": null}
]
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
%% Cell type:markdown id: tags:
### **pivot_table():** Summarize Data with a Pivot Table
We can create a pivot table to summarize sales by region and product across months:
%% Cell type:code id: tags:
```
import pandas as pd
# Sample DataFrame
data = {
'Region': ['North', 'South', 'East', 'West', 'North', 'South', 'East', 'West'],
'Product': ['A', 'A', 'B', 'B', 'A', 'B', 'A', 'B'],
'Sales': [150, 200, 130, 180, 210, 220, 170, 190],
'Quantity': [10, 15, 13, 18, 12, 22, 14, 19]
}
df = pd.DataFrame(data)
pivot_df = df.pivot_table(values='Sales', index='Region', columns='Product', aggfunc='mean')
print("\nPivot Table (Average Sales by Region and Product):")
print(pivot_df)
```
%% Output
Pivot Table (Average Sales by Region and Product):
Product A B
Region
East 170.0 130.0
North 180.0 NaN
South 200.0 220.0
West NaN 185.0
%% Cell type:code id: tags:
```
melted_df = df.melt(id_vars=['Region'], value_vars=['Product', 'Sales'], var_name='Attribute', value_name='Value')
print("\nMelted DataFrame (Unpivoted):")
print(melted_df)
```
%% Output
Melted DataFrame (Unpivoted):
Region Attribute Value
0 North Product A
1 South Product A
2 East Product B
3 West Product B
4 North Product A
5 South Product B
6 East Product A
7 West Product B
8 North Sales 150
9 South Sales 200
10 East Sales 130
11 West Sales 180
12 North Sales 210
13 South Sales 220
14 East Sales 170
15 West Sales 190
%% Cell type:code id: tags:
```
filled_pivot_df = pivot_df.fillna(value=0)
print(filled_pivot_df)
```
%% Output
Product A B
Region
East 170.0 130.0
North 180.0 0.0
South 200.0 220.0
West 0.0 185.0
%% Cell type:markdown id: tags:
**df.melt():** Unpivot from Wide to Long Format
If we want to convert the DataFrame to a long format (one column for "variable" and one for "value"), we use melt(). For example, to have a column for each attribute (Region, Month, Product, Sales), use:
%% Cell type:markdown id: tags:
### **df.stack() and df.unstack():** Reshape by Stacking and Unstacking
Let's say we have a pivot table and we want to reshape it using stack() and unstack(). For example, starting with pivot_df from above:
%% Cell type:code id: tags:
```
# Stack: Move columns (Product) into the row index level
stacked_df = pivot_df.stack()
print("\nOriginal DataFrame:")
print(pivot_df)
print("\nStacked DataFrame:")
print(stacked_df)
```
%% Output
Original DataFrame:
Product A B
Region
East 170.0 130.0
North 180.0 NaN
South 200.0 220.0
West NaN 185.0
Stacked DataFrame:
Region Product
East A 170.0
B 130.0
North A 180.0
South A 200.0
B 220.0
West B 185.0
dtype: float64
%% Cell type:markdown id: tags:
### **Delete Duplicate's**
The Pandas method to remove duplicates is ```drop_duplicates()```.
Parameters:
* Subset: Specify columns to check for duplicates, e.g., subset=['Column1', 'Column2'].
* Keep: Defines which duplicate to keep:
* first (default): Keeps the first occurrence of each duplicate.
* last: Keeps the last occurrence.
* False: Removes all duplicates.
%% Cell type:code id: tags:
```
import pandas as pd
# Sample DataFrame with Alice duplicated
data = {
'Name': ['Alice', 'Bob', 'Alice', 'Charlie', 'Bob'],
'Age': [24, 19, 24, 24, 19]
}
df = pd.DataFrame(data)
# Remove duplicates based on the 'Name' column, keeping the first occurrence
df_unique = df.drop_duplicates(subset=['Name'], keep='first')
print(df_unique)
```
%% Output
Name Age
0 Alice 24
1 Bob 19
3 Charlie 24
%% Cell type:markdown id: tags:
Parameters:
Subset: Specify columns to check for duplicates, e.g., df.drop_duplicates(subset=['Column1', 'Column2']).
Keep: Defines which duplicate to keep:
first (default): Keeps the first occurrence of each duplicate.
last: Keeps the last occurrence.
False: Removes all duplicates.
In-Place: By default, drop_duplicates() returns a new DataFrame. Set inplace=True to modify the original DataFrame directly.
%% 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("Zeile")
if 1 > 2:
print("Five is greater than two!")
print("This is a second statement.")
else:
print("The world is a disk!")
```
%% Output
Zeile
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
Cell In[2], line 2
print("Five is greater than two!")
^
IndentationError: expected an indented block
IndentationError: expected an indented block after 'if' statement on line 1
%% 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)
```
%% Output
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
%% 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)
x = "This is a string"
print(x)
```
%% 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
x = (10 < 9)
print(x)
```
%% Output
True
False
%% 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 \"guitar\" \\\" Mayer"
print(my_name)
my_name = 'John'
```
%% Output
John "guitar" \" Mayer
%% 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
full_name = first_name +"\n "+ last_name
print(full_name)
```
%% Output
John Doe
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"))
print(full_name.count("oe"))
```
%% Output
JOHN DOE
2
1
%% 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
4562233424
%% Cell type:code id: tags:
``` python
y = x
id(y)
```
%% Output
4537738384
4562233424
%% Cell type:code id: tags:
``` python
x is y
```
%% Output
True
%% Cell type:code id: tags:
``` python
x is 10.0
```
%% Output
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
/var/folders/9d/kn6wbnzj4d59jnkrn0n0qmbc0000gn/T/ipykernel_74124/938034634.py:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
x is 10.0
False
%% 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)
print(id(y))
x = y
print(id(x))
x = 12
print(id(x))
```
%% Output
4455295664
4562233424
4562233424
4518236264
%% Cell type:code id: tags:
``` python
```
%% 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:
## Input / Output
print()
%% 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
x = 7
not (x > 5 and x < 10)
```
%% Output
True
False
%% 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:
x = 4
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)
* 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
......
This diff is collapsed.
%% Cell type:markdown id:becc5c8b tags:
# Week 4: Control Strucutres II
%% Cell type:markdown id:59608955 tags:
## 1.1 While loops
%% Cell type:markdown id:5d4d9321 tags:
Write a Python program that prints numbers from 1 to 5 using a while loop.
%% Cell type:code id:d3748f44 tags:
``` python
number = 1
while number <= 5:
print(number)
number += 1
```
%% Output
1
2
3
4
5
%% Cell type:markdown id:55995920 tags:
## 1.2 Password attempt
Write a Python program that simulates alogin system. The program should allow the user to attempt entering a password up to 3 times. If the user enters the correct password, the program should display a success message and stop. If the user fails 3 times, it should lock the user out with a failure message.
The correct password is ``pythonrocks``.
%% Cell type:code id:c7a650bc tags:
``` python
loginattempts = 0
password = "pythonrocks"
loginstatus = False
while loginattempts < 3:
attempt = input("Password please")
if password == attempt:
print("login successfull")
loginstatus = True
break
else:
print("Wrong password")
loginattempts += 1
if loginattempts == 3:
print("too many attempts used you are band")
loginstatus = False
while loginstatus == False:
pass
print("✨✨✨✨✨ SYSTEM UNLOCKED ✨✨✨✨✨\n")
print(r"""
.-=========-.
\'-=======-'/
_| .=. |_
((| {{1}} |))
\| /|\ |/
\__ '`' __/
_`) (`_
_/_______\_
/___________\
You've successfully logged in!
Mission Control Online
""")
print("Enjoy your adventure! 🚀\n")
```
%% Output
login successfull
✨✨✨✨✨ SYSTEM UNLOCKED ✨✨✨✨✨
.-=========-.
\'-=======-'/
_| .=. |_
((| {{1}} |))
\| /|\ |/
\__ '`' __/
_`) (`_
_/_______\_
/___________\
You've successfully logged in!
Mission Control Online
Enjoy your adventure! 🚀
%% Cell type:markdown id:0e3d6582 tags:
## 2. for loops
%% Cell type:markdown id:b1521cf0 tags:
#### 2.1 Ausgabe einer Liste
Given a list of animals. Write a program that outputs the contents of the list
%% Cell type:code id:9d700e0f tags:
``` python
animals = ['dog', 'cat', 'bird', 'fish']
```
%% Cell type:code id:a27c48de tags:
``` python
for animal in animals:
print(animal)
```
%% Output
dog
cat
bird
fish
%% Cell type:markdown id:f00bbc4f tags:
#### 2.2 Determine the data types of list elements
Given a list with data, extend the code so that the data types of the individual variables are listed in a new list called ``type_list``
Output the newly created list with a print command
%% Cell type:code id:046a9e3f tags:
``` python
%reset -f
List = [ 3.1, "Hallo Welt", True]
```
%% Cell type:code id:693fca94 tags:
``` python
List = [3, "Hallo Welt", True]
for item in List:
print(type(item))
```
%% Output
<class 'int'>
<class 'str'>
<class 'bool'>
%% Cell type:markdown id:800d6106 tags:
#### 2.3 Prime number determination
Write a program that checks whether a given number is a prime number. <br>
Tip: **int()** can be used to convert values into integers
**Logik** A prime number is a natural number which is greater than 1 and is only divisible by itself and by 1 without remainder. <br>
**TIP:** Use the function ``range(start, stop, step)`` to generate divisors to be checked.<br>
for that the ``break`` statement can be used
%% Cell type:code id:948bddc1 tags:
``` python
Value = int(input("give me a number"))
if Value < 2:
print("Not a Prime Number")
else:
is_prime = True
for Number in range(2, Value, 1):
if Value % Number == 0:
is_prime = False # If a divisor is found, it is not prime
break #ende the loop if a prime number is found
if is_prime:
print("Prime Number")
else:
print("Not a Prime Number")
```
%% Output
Prime Number
%% Cell type:markdown id:259d8ec3 tags:
### 3 Func
%% Cell type:markdown id:53685910 tags:
#### 3.1 Palindrome checker
Implement a function called Palindrome_checker
A palindrome is a word, a sentence, a number or another sequence of characters that can be read the same forwards and backwards.
**TIP** with the slicing syntax [::-1], a string can be reversed <br>
You can use the ``.lower()`` function to ignore upper and lower case letters
%% Cell type:code id:c25c88c9 tags:
``` python
%reset -f
def palindrome_checker(word):
word = word.lower()
if word == word[::-1]:
print("is palindrome")
else:
print("not a palindrome")
print(palindrome_checker(input("what word to check")))
```
%% Output
is palindrome
None
%% Cell type:markdown id:ec6bf765 tags:
#### 3.2 Fibonacci
Implement a function called fibonacci that takes a number n as a parameter and returns the first n numbers of the Fibonacci sequence in a list.
Implementation notes:
The Fibonacci sequence starts with 0 and 1. Each additional number is the sum of the two previous numbers.
Use a loop to generate the number sequence.
> start with ``fibonacci = [0,1]`` to make programming easier
%% Cell type:code id:6807e28c tags:
``` python
def fibonacci(n):
fibonacci = [0,1]
for i in range(2,n+1,1):
nextfibonacci = fibonacci[i-1]+fibonacci[i-2]
fibonacci.append(nextfibonacci)
return fibonacci
print(fibonacci(int(input("value"))))
```
%% Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
%% Cell type:markdown id:21082eed tags:
#### 3.3 Sum of digits
Task:
Write a function called sum_of_digits that takes an integer as a parameter and returns the sum of its digits.
Implementation notes:
You can convert the number to a string to extract each digit, or use math operations to isolate the digits.
%% Cell type:code id:4f5ef8d0 tags:
``` python
def Sum_of_digits(number):
value = 0
str(number)
for digit in number:
value += int(digit)
return value
print(Sum_of_digits(input("enter a Number")))
```
%% Output
18
%% Cell type:markdown id:a15c9045 tags:
#### 3.4 Number of vowels in a string
Write a function ``count_vowels`` that takes a string as a parameter and returns the number of vowels in the string.
> **TIP:** You can use ``.lower()`` to make the function case-insensitive, ensuring it counts both uppercase and lowercase vowels.
%% Cell type:code id:ee070497 tags:
``` python
def count_vowels(word):
word = word.lower()
nvowls = 0
vowels ="aeiou"
for letter in word:
if letter in vowels:
nvowls += 1
return nvowls
print(count_vowels(str(input("word"))))
```
%% Output
9
%% Cell type:markdown id:3811ae84 tags:
# Voluntary extended tasks
%% Cell type:markdown id:77c5124c tags:
#### 4.1 Faculty calculation
- Write a function called factorial that takes a number n as a parameter and returns the factorial of this number.
- **Logic** The factorial of a number n is the product of all positive integers less than or equal to n.
> **TIP:** Use a for loop to calculate the product
%% Cell type:code id:73694875 tags:
``` python
def Faculty_calculator(value):
Faculty = 1
for i in range(2,value+1,1):
Faculty = Faculty*i
return Faculty
print(Faculty_calculator(int(input("give a number"))))
```
%% Output
120
%% Cell type:markdown id:5abd2d86 tags:
#### 4.2 Bubblesort algarythm: **for Geeks!**
Bubblesort algarythmus:
Write a function called bubble_sort that takes a list of numbers as parameters.
Implement algorithm:
Inside the function, use the bubble sort algorithm to sort the list.
The algorithm should compare and swap neighboring elements until the entire list is sorted.
Test:
Test the function with multiple lists of numbers to make sure it sorts correctly.
Implementation notes:
Bubble Sort Logic: start at the beginning of the list and compare each neighboring pair of elements. Swap the elements if the first element is greater than the second. Repeat this process for each pairing in the list, then start again from the beginning until a run without swaps has been completed.
Optimization option: You can use a variable to track whether swaps have been made. If a complete run ends without swaps, you can end the sorting as the list is already sorted.
test_array = [64, 34, 25, 12, 22, 11, 90]
%% Cell type:code id:b0ef1b7b tags:
``` python
def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Track whether any swaps were made
swapped = False
# Last i elements are sorted
for j in range(0, n-i-1):
# Swap if the element found is greater than the next element
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
# If no elements were swapped, the list is already sorted
if not swapped:
break
return arr
# Test the function with a array
test_array = [64, 34, 25, 12, 22, 11, 90]
sorted_array = bubble_sort(test_array)
print("Sorted array:", sorted_array)
```
%% Output
Sorted array: [11, 12, 22, 25, 34, 64, 90]
%% Cell type:markdown id:becc5c8b tags:
# Week 4: Control Strucutres
# Week 4: Control Strucutres II
%% Cell type:markdown id:59608955 tags:
## 1 While loops
%% Cell type:markdown id:5d4d9321 tags:
## 1.2 Basic While loop
Write a Python program that prints numbers from 1 to 5 using a while loop.
%% Cell type:code id:ca902be9 tags:
``` python
```
%% Cell type:markdown id:55995920 tags:
## 1.2 Password attempt
Write a Python program that simulates alogin system. The program should allow the user to attempt entering a password up to 3 times. If the user enters the correct password, the program should display a success message and stop. If the user fails 3 times, it should lock the user out with a failure message.
The correct password is ``pythonrocks``.
%% Cell type:code id:8e316f1b tags:
``` python
```
%% Cell type:markdown id:0e3d6582 tags:
## 1. for loops
## 2. For loops
%% Cell type:markdown id:b1521cf0 tags:
#### 1.1 Ausgabe einer Liste
#### 2.1 Ausgabe einer Liste
Given a list of animals. Write a program that outputs the contents of the list
%% Cell type:code id:9d700e0f tags:
``` python
animals = ['dog', 'cat', 'bird', 'fish']
```
%% Cell type:code id:a27c48de tags:
%% Cell type:code id:9e37533d tags:
``` python
```
%% Output
dog
cat
bird
fish
%% Cell type:markdown id:f00bbc4f tags:
#### 1.2 Determine the data types of list elements
#### 2.2 Determine the data types of list elements
Given a list with data, extend the code so that the data types of the individual variables are listed in a new list called ``type_list``
Output the newly created list with a print command
Output the newly created list with a print command. Hint: the method ```type(varaiable)``` returns then type name.
%% Cell type:code id:046a9e3f tags:
``` python
List = [ 3.1, "Hallo Welt", True]
```
%% Cell type:code id:693fca94 tags:
%% Cell type:code id:4255b571 tags:
``` python
```
%% Output
[<class 'float'>, <class 'str'>, <class 'bool'>]
%% Cell type:markdown id:800d6106 tags:
#### 1.3 Prime number determination
#### 2.3 Prime number determination
Write a program that checks whether a given number is a prime number. <br>
Tip: **int()** can be used to convert values into integers
**Logik** A prime number is a natural number which is greater than 1 and is only divisible by itself and by 1 without remainder. <br>
**TIP:** Use the function ``range(start, stop, step)`` to generate divisors to be checked.<br>
for that the ``break`` statement can be used
%% Cell type:code id:948bddc1 tags:
%% Cell type:code id:7f9daf9a tags:
``` python
```
%% Output
Die Zahl ist keine Primzahl.
%% Cell type:markdown id:259d8ec3 tags:
### 2.1 Advanced tasks
%% Cell type:markdown id:3c5b5e51 tags:
### 2.2 Checking the availability of screws in the warehouse
Define a ``screw_warehouse_manager`` function that checks whether a particular screw exists in the warehouse and whether it is in stock.
### Task
1. **Dictionary**
- Given is a dictionary 'screw warehouse' that contains different screw types and their available quantities.
2. **Implement function**
- Implement the function `Screw_warehouse_manager(screw)`, which performs the following checks:
- If the screw is available in stock and the quantity is greater than 0, the function returns `“in stock”`.
- If the screw is in stock but the quantity is 0, the function returns “out of stock”.
- If the screw is not in stock, the function returns `“does not exist”`.
%% Cell type:code id:149d200c tags:
``` python
Screw_warehouse = {
"M5": 12,
"M3": 0,
"M2.5": 6,
"M2": 20,
}
```
%% Cell type:code id:1b33ffc5 tags:
``` python
```
%% Output
out of stock
### 3 Functions
%% Cell type:markdown id:53685910 tags:
#### 2.3.1 Palindrome checker
Write a program to check whether a word is a palindrome.
#### 3.1 Palindrome checker
Implement a function called Palindrome_checker
A palindrome is a word, a sentence, a number or another sequence of characters that can be read the same forwards and backwards.
**TIP** with the slicing syntax [::-1], a string can be reversed <br>
You can use the ``.lower()`` function to ignore upper and lower case letters
%% Cell type:code id:c25c88c9 tags:
%% Cell type:code id:bcc82bd9 tags:
``` python
```
%% Output
'no palindrom'
%% Cell type:markdown id:ec6bf765 tags:
#### 2.3.2 Fibonacci
Schreiben Sie eine Funktion namens fibonacci, die eine Zahl n als Parameter nimmt und die ersten n Zahlen der Fibonacci-Folge in einer Liste zurückgibt.
#### 3.2 Fibonacci
Implement a function called fibonacci that takes a number n as a parameter and returns the first n numbers of the Fibonacci sequence in a list.
Hinweise zur Implementierung:
Implementation notes:
Die Fibonacci-Folge beginnt mit 0 und 1. Jede weitere Zahl ist die Summe der beiden vorhergehenden Zahlen.
Verwenden Sie eine Schleife, um die Zahlenfolge zu erzeugen.
The Fibonacci sequence starts with 0 and 1. Each additional number is the sum of the two previous numbers.
Use a loop to generate the number sequence.
> start with ``fibonacci = [0,1]`` to make programming easier
%% Cell type:code id:6807e28c tags:
%% Cell type:code id:565ad93a tags:
``` python
```
%% Output
[0, 1, 1, 2, 3, 5]
%% Cell type:markdown id:21082eed tags:
#### 2.3.3 Sum of digits
#### 3.3 Sum of digits
Task:
Write a function called sum_of_digits that takes an integer as a parameter and returns the sum of its digits.
Implementation notes:
You can convert the number to a string to extract each digit, or use math operations to isolate the digits.
%% Cell type:code id:4f5ef8d0 tags:
%% Cell type:code id:2db44c44 tags:
``` python
```
%% Output
10
%% Cell type:markdown id:77c5124c tags:
%% Cell type:markdown id:a15c9045 tags:
#### 2.3.4 Faculty calculation
#### 3.4 Number of vowels in a string
Write a function ``count_vowels`` that takes a string as a parameter and returns the number of vowels in the string.
- Write a function called factorial that takes a number n as a parameter and returns the factorial of this number.
- **Logic** The factorial of a number n is the product of all positive integers less than or equal to n.
> **TIP:** Use a for loop to calculate the product
> **TIP:** You can use ``.lower()`` to make the function case-insensitive, ensuring it counts both uppercase and lowercase vowels.
%% Cell type:code id:73694875 tags:
%% Cell type:code id:97e09fcc tags:
``` python
```
%% Output
%% Cell type:markdown id:3811ae84 tags:
6
# Voluntary extended tasks
%% Cell type:markdown id:a15c9045 tags:
%% Cell type:markdown id:77c5124c tags:
#### 2.3.5 Number of vowels in a string
Write a function ``count_vowels`` that takes a string as a parameter and returns the number of vowels in the string.
#### 4.1 Faculty calculation
> **TIP:** You can use ``.lower()`` to make the function case-insensitive, ensuring it counts both uppercase and lowercase vowels.
- Write a function called factorial that takes a number n as a parameter and returns the factorial of this number.
- **Logic** The factorial of a number n is the product of all positive integers less than or equal to n.
> **TIP:** Use a for loop to calculate the product
%% Cell type:code id:e7754f7b tags:
%% Cell type:code id:db0682bc tags:
``` python
```
%% Output
5
%% Cell type:markdown id:5abd2d86 tags:
#### 2.3.2 Bubblesort algarythm: **for Geeks!**
#### 4.2 Bubblesort algarythm: **for Geeks!**
Bubblesort algarythmus:
Write a function called bubble_sort that takes a list of numbers as parameters.
Implement algorithm:
Inside the function, use the bubble sort algorithm to sort the list.
The algorithm should compare and swap neighboring elements until the entire list is sorted.
Test:
Test the function with multiple lists of numbers to make sure it sorts correctly.
Implementation notes:
Bubble Sort Logic: start at the beginning of the list and compare each neighboring pair of elements. Swap the elements if the first element is greater than the second. Repeat this process for each pairing in the list, then start again from the beginning until a run without swaps has been completed.
Optimization option: You can use a variable to track whether swaps have been made. If a complete run ends without swaps, you can end the sorting as the list is already sorted.
test_array = [64, 34, 25, 12, 22, 11, 90]
%% Cell type:code id:b0ef1b7b tags:
%% Cell type:code id:7d4e526f tags:
``` python
```
......
%% 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
* 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
* To define a function, we use the `def`keyword, 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"
* However, functions can access variables of the outer scope (e.g. global variables)
* Variables in the outermost 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()ß
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
Cell In[7], 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
* 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
## More About Functions in Python
* Default Parameter Value : You can define default values, in case the function is called without parameter
* Default Parameter Value: You can define default values in case the function is called without parameters
%% 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
* Arbitrary Arguments, *args: If you do not know how many arguments 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:
# 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
* The module name can be any installed Python module,
* or the name of a file somewhere in your project (name without the '.py' ending)
* Functions in a module are accessible using 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 ``
* A module can be organized into submodules by placing them in a folder or subfolder within your project
* The module name will then be `` module.submodule `` (according to the folder 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 using the `` as `` keyword: ``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
* Fortunately we don't have to search and copy them from the internet
* Python has a 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
* A namespace is 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:
* Python recognizes 3 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
* In Python, functions, modules (and classes) act as enclosing and local namespaces
* You might have noticed: modules automatically act as a namespace
* Their structure determines the scope of names
* In terms of memory:
* Global variables remain in RAM at all times
* 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.
* While an enclosing variable x can be read in an inner namespace, a new variable will be created as soon as you assign a value to it
%% 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
......
This diff is collapsed.
%% Cell type:markdown id:41ad2b77 tags:
### 1.1 Namespace basic
Create a function that contains a nested function.
For each space (Global, outer-, and inner Function) define the variable a with different values e.g., 1,2,3 <br>
Show how the namespaces are separated from each other by using the print function in different spaces.
call the outer function ``outer_function`` and the inner function``inner_function``
%% Cell type:code id:aa5b4c1f tags:
``` python
# global
a = 1
def outer_function():
# outer function
a = 2
def inner_function():
# inner function
a = 3
print(f"Inner function scope 'a' = {a}") # This will print the inner scope variable 'a'
inner_function()
print(f"Outer function scope 'a' = {a}") # This will print the outer scope variable 'a'
# Call the outer function
outer_function()
# Print the global scope variable 'a'
print(f"Global scope 'a' = {a}")
```
%% Output
Inner function scope 'a' = 3
Outer function scope 'a' = 2
Global scope 'a' = 1
%% Cell type:markdown id:0a1c4f0d tags:
1.2 Namespace using ``global`` and ``nonlocal``
%% Cell type:markdown id:ad3e2e48 tags:
### 2.1 Declaration of data collections
Create variables with basic data types with the following names, which can store the corresponding value:
- the verbs swim run dance
- The GPS coordinates: 47.2286, 8.8317
- The definition of a person with name, age, canton of residence
%% Cell type:code id:9f98d24d tags:
``` python
#list to store the verbs: swim, run, dance
verbs = ["swim", "run", "dance"]
#tuple to store the GPS coordinates (latitude, longitude)
gps_coordinates = (47.2286, 8.8317)
# A dictionary to store a definition
person = {
"name": "John Doe",
"age": 30,
"canton": "St. Gallen"
}
# Display the variables
print("Verbs:", verbs)
print("GPS Coordinates:", gps_coordinates)
print("Person:", person)
```
%% Output
Verbs: ['swim', 'run', 'dance']
GPS Coordinates: (47.2286, 8.8317)
Person: {'name': 'John Doe', 'age': 30, 'canton': 'St. Gallen'}
%% Cell type:code id:b01c0156 tags:
``` python
# Initial
student = {
"name": "Anna",
"age": 22,
"major": "social work"
}
# Add the key "graduation_year"
student["graduation_year"] = 2025
# Remove the "age" key
student.pop("name")
# Print the updated dictionary
print("Updated student dictionary:", student)
```
%% Output
Updated student dictionary: {'age': 22, 'major': 'social work', 'graduation_year': 2025}
%% Cell type:markdown id:93970c5b tags:
### 2.3 Loop Through a Dictionary
Given the dictionary:
```python
movie = {x
"title": "Inception",
"director": "Christopher Nolan",
"release_year": 2010
}
```
Write a Python program that loops through the dictionary and prints both the keys and their corresponding values.
%% Cell type:code id:61004b7b tags:
``` python
movie = {
"title": "Inception",
"director": "Christopher Nolan",
"release_year": 2010
}
# Loop through the dictionary and print both keys and values
for key, value in movie.items():
print(f"{key}: {value}")
```
%% Output
title: Inception
director: Christopher Nolan
release_year: 2010
%% Cell type:markdown id:6b25596c tags:
### 2.4 Checking the availability of screws in the warehouse
Define a ``screw_warehouse_manager`` function that checks whether a particular screw exists in the warehouse and whether it is in stock.
### Task
1. **Dictionary**
- Given is a dictionary 'screw warehouse' that contains different screw types and their available quantities.
2. **Implement function**
- Implement the function `Screw_warehouse_manager(screw)`, which performs the following checks:
- If the screw is available in stock and the quantity is greater than 0, the function returns `“in stock”`.
- If the screw is in stock but the quantity is 0, the function returns “out of stock”.
- If the screw is not in stock, the function returns `“does not exist”`.
%% Cell type:code id:149d200c tags:
``` python
Screw_warehouse = {
"M5": 12,
"M3": 0,
"M2.5": 6,
"M2": 20,
}
```
%% Cell type:code id:1b33ffc5 tags:
``` python
def Screw_warehouse_manager(screw):
if screw in Screw_warehouse:
if Screw_warehouse[screw] > 0:
return "in stock"
else:
return "out of stock"
else:
return "This screw does not exist"
print(Screw_warehouse_manager(input("Screw Name")))
```
%% Output
in stock
%% Cell type:markdown id:0fbb59ec tags:
### 2.5 Output of component information from a BOM
Given a BOM with various machine elements, write a Python script that outputs the component information in the following form
The component _______ has the specification: ______ and is made of ________.
%% Cell type:code id:6a7edd07 tags:
``` python
bom_list = [
["Screw", "M6x30", "42CrMo4"],
["Nut", "M6", "42CrMo4"],
["Washer", "M6", "Galvanised steel"],
["Bearing", "6204", "1.3505"],
["Shaft", "Ø20x1000", "C45"],
]
```
%% Cell type:code id:a61db0cf tags:
``` python
for list in bom_list:
print("The component", list[0], "has the specification:", list[1], "and is made of", list[2], ".")
```
%% Cell type:markdown id:5fbc12e7 tags:
Now solve the same exercise this time with a dictionary <br>
**TIP:** With the ``.items()`` method you can access the key and the value of the dictionary at the same time
%% Cell type:code id:758e3e09 tags:
``` python
bom_dict = {
"Screw": ["M6x30", "42CrMo4"],
"Nut": ["M6", "42CrMo4"],
"Washer": ["M6", "Stahl verzinkt"],
"Bearing": ["6204", "1.3505"],
"Shaft": ["Ø20x1000", "C45"],
}
```
%% Cell type:code id:9388a373 tags:
``` python
for component_type, (specification, material) in bom_dict.items():
print("The component", component_type, "has the specification:", specification, "and is made of", material, ".")
```
%% Cell type:markdown id:3919aa62 tags:
### 2.6 Extract all numbers from a nested list into a single list
In this task, you are to write a Python script that extracts all numbers from a given matrix and saves them in a single list. <br>
**TIP**: additional elements can be added to a list with extend
```python
list.extend(element)
%% Cell type:code id:ddf65af1 tags:
``` python
matrix = [
[1, 2, 3, 4, 5, 6],
[10, 20, 30, 40, 50, 60],
[100, 200, 300, 400, 500, 600],
]
```
%% Cell type:code id:543433f2 tags:
``` python
extracted_numbers = []
# Loop through each sublist in the matrix and extend the extracted_numbers list
for sublist in matrix:
extracted_numbers.extend(sublist)
# Print the final list of extracted numbers
print("Extracted numbers:", extracted_numbers)
```
%% Output
Extracted numbers: [1, 2, 3, 4, 5, 6, 10, 20, 30, 40, 50, 60, 100, 200, 300, 400, 500, 600]
%% Cell type:markdown id:41ad2b77 tags:
### 1.1 Namespace basic
Create a function that contains a nested function.
For each space (Global, outer-, and inner Function) define the variable a with different values e.g., 1,2,3 <br>
Show how the namespaces are separated from each other by using the print function in different spaces.
call the outer function ``outer_function`` and the inner function``inner_function``
%% Cell type:code id:aa5b4c1f tags:
``` python
```
%% Cell type:markdown id:2cf2bba7 tags:
### 2 Data collections
Know the differences and possible uses of List, Tuple and Dictionary
%% Cell type:markdown id:ad3e2e48 tags:
### 2.1 Declaration of data collections
Create variables with basic data types with the following names, which can store the corresponding value:
- the verbs swim run dance
- The GPS coordinates: 47.2286, 8.8317
- The definition of a person with name, age, canton of residence
%% Cell type:code id:9f98d24d tags:
``` python
```
%% Cell type:markdown id:bfc3bf9b tags:
### 2.2 Add and Remove Items from a Dictionary
Start with the following dictionary:
```python
student = {
"name": "Anna",
"age": 22,
"major": "social work"
}
```
* Add a new key "graduation_year" with the value 2025.
* Remove the "age" key from the dictionary.
* Print the updated dictionary
%% Cell type:code id:b01c0156 tags:
``` python
```
%% Cell type:markdown id:93970c5b tags:
### 2.3 Loop Through a Dictionary
Given the dictionary:
```python
movie = {
"title": "Inception",
"director": "Christopher Nolan",
"release_year": 2010
}
```
Write a Python program that loops through the dictionary and prints both the keys and their corresponding values.
%% Cell type:code id:61004b7b tags:
``` python
```
%% Cell type:markdown id:6b25596c tags:
### 2.4 Checking the availability of screws in the warehouse
Define a ``screw_warehouse_manager`` function that checks whether a particular screw exists in the warehouse and whether it is in stock.
### Task
1. **Dictionary**
- Given is a dictionary 'screw warehouse' that contains different screw types and their available quantities.
2. **Implement function**
- Implement the function `Screw_warehouse_manager(screw)`, which performs the following checks:
- If the screw is available in stock and the quantity is greater than 0, the function returns `“in stock”`.
- If the screw is in stock but the quantity is 0, the function returns “out of stock”.
- If the screw is not in stock, the function returns `“does not exist”`.
%% Cell type:code id:149d200c tags:
``` python
Screw_warehouse = {
"M5": 12,
"M3": 0,
"M2.5": 6,
"M2": 20,
}
```
%% Cell type:code id:1b33ffc5 tags:
``` python
```
%% Cell type:markdown id:0fbb59ec tags:
### 2.5 Output of component information from a BOM
Given a BOM with various machine elements, write a Python script that outputs the component information in the following form
The component _______ has the specification: ______ and is made of ________.
%% Cell type:code id:6a7edd07 tags:
``` python
bom_list = [
["Screw", "M6x30", "42CrMo4"],
["Nut", "M6", "42CrMo4"],
["Washer", "M6", "Galvanised steel"],
["Bearing", "6204", "1.3505"],
["Shaft", "Ø20x1000", "C45"],
]
```
%% Cell type:code id:a61db0cf tags:
``` python
```
%% Cell type:markdown id:5fbc12e7 tags:
Now solve the same exercise this time with a dictionary <br>
**TIP:** With the ``.items()`` method you can access the key and the value of the dictionary at the same time
%% Cell type:code id:758e3e09 tags:
``` python
bom_dict = {
"Screw": ["M6x30", "42CrMo4"],
"Nut": ["M6", "42CrMo4"],
"Washer": ["M6", "Stahl verzinkt"],
"Bearing": ["6204", "1.3505"],
"Shaft": ["Ø20x1000", "C45"],
}
```
%% Cell type:code id:9388a373 tags:
``` python
```
%% Cell type:markdown id:3919aa62 tags:
### 2.6 Extract all numbers from a nested list into a single list
In this task, you are to write a Python script that extracts all numbers from a given matrix and saves them in a single list. <br>
**TIP**: additional elements can be added to a list with extend
```python
list.extend(element)
%% Cell type:code id:ddf65af1 tags:
``` python
matrix = [
[1, 2, 3, 4, 5, 6],
[10, 20, 30, 40, 50, 60],
[100, 200, 300, 400, 500, 600],
]
```
%% Cell type:code id:543433f2 tags:
``` python
```
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Example 1,Example 2,Example 3,Example 4,Example 5
Word1,Word21,Word41,,Word81
Word2,Word22,Word42,,Word82
Word3,Word23,Word43,Word63,
Word4,Word24,,,Word84
Word5,,Word45,,Word85
Word6,Word26,Word46,Word66,
Word7,,,Word67,Word87
Word8,Word28,,,
Word9,Word29,Word49,Word69,Word89
Word10,Word30,Word50,,Word90
Word11,,Word51,Word71,Word91
Word12,Word32,Word52,Word72,Word92
Word13,Word33,Word53,Word73,
Word14,Word34,,Word74,Word94
,Word37,Word57,,Word97
Word18,Word38,,,
Word19,Word39,Word59,,Word99
Word20,Word40,,,