Skip to content
Snippets Groups Projects
Commit f5b9aed7 authored by Jöran Frey's avatar Jöran Frey
Browse files

added solution week 5 added content to lecture

parent dbd77cfd
No related branches found
No related tags found
No related merge requests found
%% 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]
{
"store": {
"name": "TechGadget Online",
"location": "San Francisco",
"currency": "USD"
},
"products": [
{
"id": 101,
"name": "Wireless Mouse",
"brand": "LogiTech",
"price": 29.99,
"stock": 150,
"categories": ["Electronics", "Accessories"],
"rating": 4.7,
"available": true
},
{
"id": 102,
"name": "Bluetooth Speaker",
"brand": "JBL",
"price": 89.99,
"stock": 85,
"categories": ["Electronics", "Audio"],
"rating": 4.5,
"available": true
},
{
"id": 103,
"name": "Gaming Keyboard",
"brand": "Razer",
"price": 119.99,
"stock": 45,
"categories": ["Electronics", "Accessories"],
"rating": 4.8,
"available": false
}
]
}
\ No newline at end of file
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