Spaces:
Running
Running
Merge pull request #14 from marimo-team/aka/reorg-python
Browse files- Python/phase_1/number_operations.py → python/001_numbers.py +59 -41
- Python/phase_1/string_manipulation.py → python/002_strings.py +79 -47
- Python/phase_1/collections.py → python/003_collections.py +23 -37
- Python/phase_2/conditional_logic.py → python/004_conditional_logic.py +101 -60
- Python/phase_2/loop_structures.py → python/005_loops.py +80 -79
- Python/phase_3/dictionaries.py → python/006_dictionaries.py +94 -100
- Python/phase_3/advanced_collections.py → python/007_advanced_collections.py +41 -37
- Python/phase_4/function_design.py → python/008_functions.py +74 -117
- Python/phase_4/modular_programming.py → python/009_modules.py +31 -80
- Python/phase_5/error_management.py → python/010_exceptions.py +70 -128
- {Python → python}/README.md +0 -0
Python/phase_1/number_operations.py → python/001_numbers.py
RENAMED
|
@@ -7,25 +7,20 @@
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
-
__generated_with = "0.10.
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
| 14 |
-
@app.cell
|
| 15 |
-
def _():
|
| 16 |
-
import marimo as mo
|
| 17 |
-
return (mo,)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
@app.cell(hide_code=True)
|
| 21 |
def _(mo):
|
| 22 |
mo.md(
|
| 23 |
"""
|
| 24 |
-
# 🔢 Numbers
|
| 25 |
|
| 26 |
-
|
| 27 |
|
| 28 |
## Number Types
|
|
|
|
| 29 |
Python has several types of numbers:
|
| 30 |
|
| 31 |
```python
|
|
@@ -50,7 +45,7 @@ def _():
|
|
| 50 |
def _(mo):
|
| 51 |
mo.md(
|
| 52 |
"""
|
| 53 |
-
## Basic
|
| 54 |
|
| 55 |
Python supports all standard mathematical operations.
|
| 56 |
|
|
@@ -104,15 +99,15 @@ def _(number):
|
|
| 104 |
|
| 105 |
@app.cell
|
| 106 |
def _(number):
|
| 107 |
-
number
|
| 108 |
return
|
| 109 |
|
| 110 |
|
| 111 |
-
@app.cell
|
| 112 |
def _(mo):
|
| 113 |
mo.md(
|
| 114 |
"""
|
| 115 |
-
## Type
|
| 116 |
|
| 117 |
You can convert between different number types. Try changing these values!
|
| 118 |
"""
|
|
@@ -134,7 +129,7 @@ def _(decimal_number):
|
|
| 134 |
|
| 135 |
@app.cell
|
| 136 |
def _(number):
|
| 137 |
-
float(number) # Convert to float
|
| 138 |
return
|
| 139 |
|
| 140 |
|
|
@@ -142,7 +137,7 @@ def _(number):
|
|
| 142 |
def _(mo):
|
| 143 |
mo.md(
|
| 144 |
"""
|
| 145 |
-
## Built-in
|
| 146 |
Python provides many useful built-in functions for working with numbers:
|
| 147 |
"""
|
| 148 |
)
|
|
@@ -177,51 +172,74 @@ def _():
|
|
| 177 |
def _(mo):
|
| 178 |
mo.md(
|
| 179 |
"""
|
| 180 |
-
## Advanced
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
-
For more complex mathematical operations, Python's `math` module is your friend:
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
| 186 |
|
| 187 |
-
# Square root
|
| 188 |
-
math.sqrt(16) # 4.0
|
| 189 |
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
|
|
|
| 193 |
|
| 194 |
-
# Constants
|
| 195 |
-
math.pi # 3.141592653589793
|
| 196 |
-
math.e # 2.718281828459045
|
| 197 |
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
return
|
| 205 |
|
| 206 |
|
| 207 |
@app.cell(hide_code=True)
|
| 208 |
def _(mo):
|
| 209 |
-
|
| 210 |
-
##
|
| 211 |
-
|
| 212 |
-
Next Steps:
|
| 213 |
|
| 214 |
- Practice different mathematical operations
|
| 215 |
-
|
| 216 |
- Experiment with type conversions
|
| 217 |
-
|
| 218 |
- Try out the math module functions
|
| 219 |
|
| 220 |
Keep calculating! 🧮✨
|
| 221 |
""")
|
|
|
|
| 222 |
|
| 223 |
-
|
| 224 |
-
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
|
| 227 |
if __name__ == "__main__":
|
|
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
+
__generated_with = "0.10.19"
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
@app.cell(hide_code=True)
|
| 15 |
def _(mo):
|
| 16 |
mo.md(
|
| 17 |
"""
|
| 18 |
+
# 🔢 Numbers
|
| 19 |
|
| 20 |
+
This tutorial provides a brief overview of working with numbers.
|
| 21 |
|
| 22 |
## Number Types
|
| 23 |
+
|
| 24 |
Python has several types of numbers:
|
| 25 |
|
| 26 |
```python
|
|
|
|
| 45 |
def _(mo):
|
| 46 |
mo.md(
|
| 47 |
"""
|
| 48 |
+
## Basic mathematical operations
|
| 49 |
|
| 50 |
Python supports all standard mathematical operations.
|
| 51 |
|
|
|
|
| 99 |
|
| 100 |
@app.cell
|
| 101 |
def _(number):
|
| 102 |
+
number**2 # Exponentiation
|
| 103 |
return
|
| 104 |
|
| 105 |
|
| 106 |
+
@app.cell(hide_code=True)
|
| 107 |
def _(mo):
|
| 108 |
mo.md(
|
| 109 |
"""
|
| 110 |
+
## Type conversion
|
| 111 |
|
| 112 |
You can convert between different number types. Try changing these values!
|
| 113 |
"""
|
|
|
|
| 129 |
|
| 130 |
@app.cell
|
| 131 |
def _(number):
|
| 132 |
+
float(number) # Convert to "float" or decimal
|
| 133 |
return
|
| 134 |
|
| 135 |
|
|
|
|
| 137 |
def _(mo):
|
| 138 |
mo.md(
|
| 139 |
"""
|
| 140 |
+
## Built-in math functions
|
| 141 |
Python provides many useful built-in functions for working with numbers:
|
| 142 |
"""
|
| 143 |
)
|
|
|
|
| 172 |
def _(mo):
|
| 173 |
mo.md(
|
| 174 |
"""
|
| 175 |
+
## Advanced operations
|
| 176 |
+
|
| 177 |
+
For more complex mathematical operations, use Python's [math module](https://docs.python.org/3/library/math.html).
|
| 178 |
+
"""
|
| 179 |
+
)
|
| 180 |
+
return
|
| 181 |
|
|
|
|
| 182 |
|
| 183 |
+
@app.cell
|
| 184 |
+
def _():
|
| 185 |
+
import math
|
| 186 |
+
return (math,)
|
| 187 |
|
|
|
|
|
|
|
| 188 |
|
| 189 |
+
@app.cell
|
| 190 |
+
def _(math):
|
| 191 |
+
math.sqrt(16)
|
| 192 |
+
return
|
| 193 |
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
+
@app.cell
|
| 196 |
+
def _(math):
|
| 197 |
+
math.sin(math.pi/2)
|
| 198 |
+
return
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@app.cell
|
| 202 |
+
def _(math):
|
| 203 |
+
math.cos(0)
|
| 204 |
+
return
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
@app.cell
|
| 208 |
+
def _(math):
|
| 209 |
+
math.pi, math.e
|
| 210 |
+
return
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@app.cell
|
| 214 |
+
def _(math):
|
| 215 |
+
math.log10(100)
|
| 216 |
+
return
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
@app.cell
|
| 220 |
+
def _(math):
|
| 221 |
+
math.log(math.e)
|
| 222 |
return
|
| 223 |
|
| 224 |
|
| 225 |
@app.cell(hide_code=True)
|
| 226 |
def _(mo):
|
| 227 |
+
mo.md("""
|
| 228 |
+
## Next steps:
|
|
|
|
|
|
|
| 229 |
|
| 230 |
- Practice different mathematical operations
|
|
|
|
| 231 |
- Experiment with type conversions
|
|
|
|
| 232 |
- Try out the math module functions
|
| 233 |
|
| 234 |
Keep calculating! 🧮✨
|
| 235 |
""")
|
| 236 |
+
return
|
| 237 |
|
| 238 |
+
|
| 239 |
+
@app.cell
|
| 240 |
+
def _():
|
| 241 |
+
import marimo as mo
|
| 242 |
+
return (mo,)
|
| 243 |
|
| 244 |
|
| 245 |
if __name__ == "__main__":
|
Python/phase_1/string_manipulation.py → python/002_strings.py
RENAMED
|
@@ -7,14 +7,8 @@
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
-
__generated_with = "0.10.
|
| 11 |
-
app = marimo.App()
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
@app.cell
|
| 15 |
-
def _():
|
| 16 |
-
import marimo as mo
|
| 17 |
-
return (mo,)
|
| 18 |
|
| 19 |
|
| 20 |
@app.cell(hide_code=True)
|
|
@@ -23,15 +17,25 @@ def _(mo):
|
|
| 23 |
"""
|
| 24 |
# 🎭 Strings
|
| 25 |
|
| 26 |
-
|
| 27 |
|
| 28 |
## Creating strings
|
| 29 |
-
|
| 30 |
-
ways:
|
| 31 |
|
| 32 |
```python
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
```
|
| 36 |
|
| 37 |
Below is an example string.
|
|
@@ -42,7 +46,8 @@ def _(mo):
|
|
| 42 |
|
| 43 |
@app.cell
|
| 44 |
def _():
|
| 45 |
-
text = "Python is amazing"
|
|
|
|
| 46 |
return (text,)
|
| 47 |
|
| 48 |
|
|
@@ -63,6 +68,7 @@ def _(mo):
|
|
| 63 |
|
| 64 |
@app.cell
|
| 65 |
def _(text):
|
|
|
|
| 66 |
len(text)
|
| 67 |
return
|
| 68 |
|
|
@@ -93,7 +99,8 @@ def _(mo):
|
|
| 93 |
|
| 94 |
@app.cell
|
| 95 |
def _(text):
|
| 96 |
-
|
|
|
|
| 97 |
return
|
| 98 |
|
| 99 |
|
|
@@ -109,7 +116,7 @@ def _(text):
|
|
| 109 |
return
|
| 110 |
|
| 111 |
|
| 112 |
-
@app.cell
|
| 113 |
def _(mo):
|
| 114 |
mo.md(
|
| 115 |
"""
|
|
@@ -118,7 +125,7 @@ def _(mo):
|
|
| 118 |
Modern Python uses f-strings to insert values into strings. For example,
|
| 119 |
check out how the next cell greets you (and notice the `f''''`)!
|
| 120 |
|
| 121 |
-
Try
|
| 122 |
"""
|
| 123 |
)
|
| 124 |
return
|
|
@@ -126,7 +133,7 @@ def _(mo):
|
|
| 126 |
|
| 127 |
@app.cell
|
| 128 |
def _():
|
| 129 |
-
my_name =
|
| 130 |
return (my_name,)
|
| 131 |
|
| 132 |
|
|
@@ -140,7 +147,7 @@ def _(my_name):
|
|
| 140 |
def _(mo):
|
| 141 |
mo.md(
|
| 142 |
"""
|
| 143 |
-
## Working with
|
| 144 |
You can access any part of a string using its position (index):
|
| 145 |
"""
|
| 146 |
)
|
|
@@ -181,48 +188,73 @@ def _(mo):
|
|
| 181 |
"""
|
| 182 |
## Other helpful string methods
|
| 183 |
|
| 184 |
-
Finally, here are some other helpful string methods. Feel free to try them out on your own strings
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
-
```python
|
| 187 |
-
sentence = " python is fun "
|
| 188 |
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
-
# Split into a list of words
|
| 193 |
-
print(sentence.split()) # ['python', 'is', 'fun']
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
"""
|
| 204 |
-
)
|
| 205 |
return
|
| 206 |
|
| 207 |
|
| 208 |
-
@app.cell
|
| 209 |
-
def _(
|
| 210 |
-
|
| 211 |
-
|
| 212 |
|
| 213 |
-
Next Steps:
|
| 214 |
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
-
You're doing great! 🐍✨
|
| 222 |
-
""")
|
| 223 |
|
| 224 |
-
|
| 225 |
-
|
|
|
|
|
|
|
| 226 |
|
| 227 |
|
| 228 |
if __name__ == "__main__":
|
|
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
+
__generated_with = "0.10.19"
|
| 11 |
+
app = marimo.App(width="medium")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
@app.cell(hide_code=True)
|
|
|
|
| 17 |
"""
|
| 18 |
# 🎭 Strings
|
| 19 |
|
| 20 |
+
This notebook introduces **strings**, which are containers for text.
|
| 21 |
|
| 22 |
## Creating strings
|
| 23 |
+
Create strings by wrapping text in quotes:
|
|
|
|
| 24 |
|
| 25 |
```python
|
| 26 |
+
# Use double quotes
|
| 27 |
+
greeting = "Hello, Python!"
|
| 28 |
+
|
| 29 |
+
# or single quotes
|
| 30 |
+
name = 'Alice'
|
| 31 |
+
|
| 32 |
+
# or triple quotes
|
| 33 |
+
multiline_string = \"""
|
| 34 |
+
Dear, Alice,
|
| 35 |
+
Nice to meet you.
|
| 36 |
+
Sincerely,
|
| 37 |
+
Bob.
|
| 38 |
+
\"""
|
| 39 |
```
|
| 40 |
|
| 41 |
Below is an example string.
|
|
|
|
| 46 |
|
| 47 |
@app.cell
|
| 48 |
def _():
|
| 49 |
+
text = "Python is amazing!"
|
| 50 |
+
text
|
| 51 |
return (text,)
|
| 52 |
|
| 53 |
|
|
|
|
| 68 |
|
| 69 |
@app.cell
|
| 70 |
def _(text):
|
| 71 |
+
# the `len` method returns the number of characters in the string.
|
| 72 |
len(text)
|
| 73 |
return
|
| 74 |
|
|
|
|
| 99 |
|
| 100 |
@app.cell
|
| 101 |
def _(text):
|
| 102 |
+
# Returns the index of "is" in the string
|
| 103 |
+
text.find("is")
|
| 104 |
return
|
| 105 |
|
| 106 |
|
|
|
|
| 116 |
return
|
| 117 |
|
| 118 |
|
| 119 |
+
@app.cell(hide_code=True)
|
| 120 |
def _(mo):
|
| 121 |
mo.md(
|
| 122 |
"""
|
|
|
|
| 125 |
Modern Python uses f-strings to insert values into strings. For example,
|
| 126 |
check out how the next cell greets you (and notice the `f''''`)!
|
| 127 |
|
| 128 |
+
**Try it!** Enter your name in `my_name` below, then run the cell.
|
| 129 |
"""
|
| 130 |
)
|
| 131 |
return
|
|
|
|
| 133 |
|
| 134 |
@app.cell
|
| 135 |
def _():
|
| 136 |
+
my_name = ""
|
| 137 |
return (my_name,)
|
| 138 |
|
| 139 |
|
|
|
|
| 147 |
def _(mo):
|
| 148 |
mo.md(
|
| 149 |
"""
|
| 150 |
+
## Working with parts of strings
|
| 151 |
You can access any part of a string using its position (index):
|
| 152 |
"""
|
| 153 |
)
|
|
|
|
| 188 |
"""
|
| 189 |
## Other helpful string methods
|
| 190 |
|
| 191 |
+
Finally, here are some other helpful string methods. Feel free to try them out on your own strings by modifying the value of `sentence` below.
|
| 192 |
+
"""
|
| 193 |
+
)
|
| 194 |
+
return
|
| 195 |
|
|
|
|
|
|
|
| 196 |
|
| 197 |
+
@app.cell
|
| 198 |
+
def _():
|
| 199 |
+
sentence = " python is fun "
|
| 200 |
+
sentence
|
| 201 |
+
return (sentence,)
|
| 202 |
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
@app.cell
|
| 205 |
+
def _(sentence):
|
| 206 |
+
# Remove extra spaces
|
| 207 |
+
sentence.strip()
|
| 208 |
+
return
|
| 209 |
|
| 210 |
+
|
| 211 |
+
@app.cell
|
| 212 |
+
def _(sentence):
|
| 213 |
+
# Split into a list of words
|
| 214 |
+
sentence.split()
|
|
|
|
|
|
|
| 215 |
return
|
| 216 |
|
| 217 |
|
| 218 |
+
@app.cell
|
| 219 |
+
def _(sentence):
|
| 220 |
+
sentence.replace("fun", "awesome")
|
| 221 |
+
return
|
| 222 |
|
|
|
|
| 223 |
|
| 224 |
+
@app.cell
|
| 225 |
+
def _():
|
| 226 |
+
"123".isdigit(), "abc".isdigit()
|
| 227 |
+
return
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
@app.cell
|
| 231 |
+
def _():
|
| 232 |
+
"123".isalpha(), "abc".isalpha()
|
| 233 |
+
return
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@app.cell
|
| 237 |
+
def _():
|
| 238 |
+
"Python3".isalnum()
|
| 239 |
+
return
|
| 240 |
+
|
| 241 |
|
| 242 |
+
@app.cell(hide_code=True)
|
| 243 |
+
def _(mo):
|
| 244 |
+
mo.md(
|
| 245 |
+
r"""
|
| 246 |
+
## Next steps
|
| 247 |
|
| 248 |
+
For a full primer on strings, check out the [official documentation](https://docs.python.org/3/library/string.html).
|
| 249 |
+
"""
|
| 250 |
+
)
|
| 251 |
+
return
|
| 252 |
|
|
|
|
|
|
|
| 253 |
|
| 254 |
+
@app.cell
|
| 255 |
+
def _():
|
| 256 |
+
import marimo as mo
|
| 257 |
+
return (mo,)
|
| 258 |
|
| 259 |
|
| 260 |
if __name__ == "__main__":
|
Python/phase_1/collections.py → python/003_collections.py
RENAMED
|
@@ -7,23 +7,17 @@
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
-
__generated_with = "0.10.
|
| 11 |
-
app = marimo.App()
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
@app.cell
|
| 15 |
-
def _():
|
| 16 |
-
import marimo as mo
|
| 17 |
-
return (mo,)
|
| 18 |
|
| 19 |
|
| 20 |
@app.cell(hide_code=True)
|
| 21 |
def _(mo):
|
| 22 |
mo.md(
|
| 23 |
"""
|
| 24 |
-
# 📦 Collections
|
| 25 |
|
| 26 |
-
|
| 27 |
|
| 28 |
## Lists
|
| 29 |
Lists are ordered, mutable sequences. Create them using square brackets:
|
|
@@ -31,7 +25,7 @@ def _(mo):
|
|
| 31 |
```python
|
| 32 |
fruits = ["apple", "banana", "orange"]
|
| 33 |
numbers = [1, 2, 3, 4, 5]
|
| 34 |
-
mixed = [1, "hello", 3.14, True]
|
| 35 |
```
|
| 36 |
|
| 37 |
Below is an example list we'll use to explore operations.
|
|
@@ -50,7 +44,7 @@ def _():
|
|
| 50 |
def _(mo):
|
| 51 |
mo.md(
|
| 52 |
"""
|
| 53 |
-
## List
|
| 54 |
|
| 55 |
Here are common operations you can perform on lists.
|
| 56 |
|
|
@@ -68,7 +62,7 @@ def _(sample_list):
|
|
| 68 |
|
| 69 |
@app.cell
|
| 70 |
def _(sample_list):
|
| 71 |
-
extended_list = sample_list + [6]
|
| 72 |
extended_list
|
| 73 |
return (extended_list,)
|
| 74 |
|
|
@@ -122,7 +116,6 @@ def _():
|
|
| 122 |
tuple2 = (4, 5, 6)
|
| 123 |
|
| 124 |
tuple3 = tuple1 + tuple2
|
| 125 |
-
|
| 126 |
tuple3
|
| 127 |
return tuple1, tuple2, tuple3
|
| 128 |
|
|
@@ -141,11 +134,7 @@ def _(mo):
|
|
| 141 |
|
| 142 |
@app.cell
|
| 143 |
def _():
|
| 144 |
-
person = {
|
| 145 |
-
"name": "John Doe",
|
| 146 |
-
"age": 25,
|
| 147 |
-
"city": "New York"
|
| 148 |
-
}
|
| 149 |
return (person,)
|
| 150 |
|
| 151 |
|
|
@@ -187,24 +176,21 @@ def _():
|
|
| 187 |
|
| 188 |
@app.cell
|
| 189 |
def _(numbers_set):
|
| 190 |
-
numbers_set
|
| 191 |
-
numbers_set
|
| 192 |
return
|
| 193 |
|
| 194 |
|
| 195 |
@app.cell
|
| 196 |
def _():
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
set1.intersection(set2) # Find common elements
|
| 200 |
-
return set1, set2
|
| 201 |
|
| 202 |
|
| 203 |
@app.cell(hide_code=True)
|
| 204 |
def _(mo):
|
| 205 |
mo.md(
|
| 206 |
"""
|
| 207 |
-
## Collection
|
| 208 |
|
| 209 |
Here are some common operations across collections:
|
| 210 |
|
|
@@ -234,20 +220,20 @@ def _(mo):
|
|
| 234 |
|
| 235 |
@app.cell(hide_code=True)
|
| 236 |
def _(mo):
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
Next Steps:
|
| 241 |
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
|
|
|
| 245 |
|
| 246 |
-
Keep organizing data! 🗃️✨
|
| 247 |
-
""")
|
| 248 |
|
| 249 |
-
|
| 250 |
-
|
|
|
|
|
|
|
| 251 |
|
| 252 |
|
| 253 |
if __name__ == "__main__":
|
|
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
+
__generated_with = "0.10.19"
|
| 11 |
+
app = marimo.App(width="medium")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
@app.cell(hide_code=True)
|
| 15 |
def _(mo):
|
| 16 |
mo.md(
|
| 17 |
"""
|
| 18 |
+
# 📦 Collections
|
| 19 |
|
| 20 |
+
A "collection" is a type of variable that holds multiple values.
|
| 21 |
|
| 22 |
## Lists
|
| 23 |
Lists are ordered, mutable sequences. Create them using square brackets:
|
|
|
|
| 25 |
```python
|
| 26 |
fruits = ["apple", "banana", "orange"]
|
| 27 |
numbers = [1, 2, 3, 4, 5]
|
| 28 |
+
mixed = [1, "hello", 3.14, True]
|
| 29 |
```
|
| 30 |
|
| 31 |
Below is an example list we'll use to explore operations.
|
|
|
|
| 44 |
def _(mo):
|
| 45 |
mo.md(
|
| 46 |
"""
|
| 47 |
+
## List operations
|
| 48 |
|
| 49 |
Here are common operations you can perform on lists.
|
| 50 |
|
|
|
|
| 62 |
|
| 63 |
@app.cell
|
| 64 |
def _(sample_list):
|
| 65 |
+
extended_list = sample_list + [6] # Concatenate two lists
|
| 66 |
extended_list
|
| 67 |
return (extended_list,)
|
| 68 |
|
|
|
|
| 116 |
tuple2 = (4, 5, 6)
|
| 117 |
|
| 118 |
tuple3 = tuple1 + tuple2
|
|
|
|
| 119 |
tuple3
|
| 120 |
return tuple1, tuple2, tuple3
|
| 121 |
|
|
|
|
| 134 |
|
| 135 |
@app.cell
|
| 136 |
def _():
|
| 137 |
+
person = {"name": "John Doe", "age": 25, "city": "New York"}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
return (person,)
|
| 139 |
|
| 140 |
|
|
|
|
| 176 |
|
| 177 |
@app.cell
|
| 178 |
def _(numbers_set):
|
| 179 |
+
numbers_set | {4} # Add a new element
|
|
|
|
| 180 |
return
|
| 181 |
|
| 182 |
|
| 183 |
@app.cell
|
| 184 |
def _():
|
| 185 |
+
{1, 2, 3} & {3, 4, 5} # Find common elements
|
| 186 |
+
return
|
|
|
|
|
|
|
| 187 |
|
| 188 |
|
| 189 |
@app.cell(hide_code=True)
|
| 190 |
def _(mo):
|
| 191 |
mo.md(
|
| 192 |
"""
|
| 193 |
+
## Collection methods and operations
|
| 194 |
|
| 195 |
Here are some common operations across collections:
|
| 196 |
|
|
|
|
| 220 |
|
| 221 |
@app.cell(hide_code=True)
|
| 222 |
def _(mo):
|
| 223 |
+
mo.md(
|
| 224 |
+
r"""
|
| 225 |
+
## Documentation
|
|
|
|
| 226 |
|
| 227 |
+
See the official [Python tutorial on data structures](https://docs.python.org/3/tutorial/datastructures.html) for more in-depth information.
|
| 228 |
+
"""
|
| 229 |
+
)
|
| 230 |
+
return
|
| 231 |
|
|
|
|
|
|
|
| 232 |
|
| 233 |
+
@app.cell
|
| 234 |
+
def _():
|
| 235 |
+
import marimo as mo
|
| 236 |
+
return (mo,)
|
| 237 |
|
| 238 |
|
| 239 |
if __name__ == "__main__":
|
Python/phase_2/conditional_logic.py → python/004_conditional_logic.py
RENAMED
|
@@ -7,23 +7,18 @@
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
-
__generated_with = "0.10.
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
| 14 |
-
@app.cell
|
| 15 |
-
def _():
|
| 16 |
-
import marimo as mo
|
| 17 |
-
return (mo,)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
@app.cell(hide_code=True)
|
| 21 |
def _(mo):
|
| 22 |
mo.md(
|
| 23 |
"""
|
| 24 |
-
# 🔄 Conditional
|
| 25 |
|
| 26 |
-
|
|
|
|
| 27 |
|
| 28 |
## If Statements
|
| 29 |
The foundation of decision-making in Python:
|
|
@@ -41,21 +36,43 @@ def _(mo):
|
|
| 41 |
return
|
| 42 |
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
@app.cell
|
| 45 |
def _():
|
| 46 |
number = 42
|
| 47 |
return (number,)
|
| 48 |
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
@app.cell
|
| 51 |
-
def _(number):
|
| 52 |
-
if number >
|
| 53 |
-
result = "Greater than
|
| 54 |
elif number == 42:
|
| 55 |
-
result = "
|
| 56 |
else:
|
| 57 |
-
result = "Less than
|
| 58 |
-
result
|
| 59 |
return (result,)
|
| 60 |
|
| 61 |
|
|
@@ -63,27 +80,27 @@ def _(number):
|
|
| 63 |
def _(mo):
|
| 64 |
mo.md(
|
| 65 |
r"""
|
| 66 |
-
|
| 67 |
-
Try changing the conditions below and see how the results change
|
| 68 |
"""
|
| 69 |
)
|
| 70 |
return
|
| 71 |
|
| 72 |
|
| 73 |
-
@app.cell
|
| 74 |
def _(mo, threshold, value):
|
| 75 |
-
mo.hstack([value, threshold])
|
| 76 |
return
|
| 77 |
|
| 78 |
|
| 79 |
-
@app.cell
|
| 80 |
def _(mo):
|
| 81 |
value = mo.ui.number(value=25, start=0, stop=100, label="Enter a number")
|
| 82 |
threshold = mo.ui.slider(value=50, start=0, stop=100, label="Set threshold")
|
| 83 |
return threshold, value
|
| 84 |
|
| 85 |
|
| 86 |
-
@app.cell
|
| 87 |
def _(mo, threshold, value):
|
| 88 |
if value.value > threshold.value:
|
| 89 |
decision = f"{value.value} is greater than {threshold.value}"
|
|
@@ -95,9 +112,11 @@ def _(mo, threshold, value):
|
|
| 95 |
mo.hstack(
|
| 96 |
[
|
| 97 |
mo.md(f"**Decision**: {decision}"),
|
| 98 |
-
mo.md(
|
|
|
|
|
|
|
| 99 |
],
|
| 100 |
-
justify="space-
|
| 101 |
)
|
| 102 |
return (decision,)
|
| 103 |
|
|
@@ -106,7 +125,7 @@ def _(mo, threshold, value):
|
|
| 106 |
def _(mo):
|
| 107 |
mo.md(
|
| 108 |
r"""
|
| 109 |
-
## Boolean
|
| 110 |
Python uses boolean operators to combine conditions:
|
| 111 |
|
| 112 |
- `and`: Both conditions must be True
|
|
@@ -119,36 +138,50 @@ def _(mo):
|
|
| 119 |
return
|
| 120 |
|
| 121 |
|
| 122 |
-
@app.cell
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
def _(age, has_id, mo):
|
| 124 |
-
mo.hstack([age, has_id])
|
| 125 |
return
|
| 126 |
|
| 127 |
|
| 128 |
-
@app.cell
|
| 129 |
def _(mo):
|
| 130 |
age = mo.ui.number(value=18, start=0, stop=120, label="Age")
|
| 131 |
has_id = mo.ui.switch(value=True, label="Has ID")
|
| 132 |
return age, has_id
|
| 133 |
|
| 134 |
|
| 135 |
-
@app.cell
|
| 136 |
def _(age, has_id, mo):
|
| 137 |
can_vote = age.value >= 18 and has_id.value
|
| 138 |
|
| 139 |
explanation = f"""
|
| 140 |
-
### Voting
|
| 141 |
|
| 142 |
Current Status:
|
| 143 |
|
| 144 |
- Age: {age.value} years old
|
| 145 |
|
| 146 |
-
- Has ID: {
|
| 147 |
|
| 148 |
-
- Can Vote: {
|
| 149 |
|
| 150 |
-
Reason: {
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
| 152 |
"""
|
| 153 |
|
| 154 |
mo.md(explanation)
|
|
@@ -157,20 +190,27 @@ def _(age, has_id, mo):
|
|
| 157 |
|
| 158 |
@app.cell(hide_code=True)
|
| 159 |
def _(mo):
|
| 160 |
-
|
| 161 |
-
- Try different combinations of age and ID status
|
| 162 |
-
- Notice how both conditions must be True to allow voting
|
| 163 |
-
- Experiment with edge cases (exactly 18, no ID, etc.)
|
| 164 |
-
""")
|
| 165 |
-
mo.accordion({"💡 Experiment Tips": _text})
|
| 166 |
return
|
| 167 |
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
@app.cell(hide_code=True)
|
| 170 |
def _(mo):
|
| 171 |
mo.md(
|
| 172 |
"""
|
| 173 |
-
## Complex
|
| 174 |
Combine multiple conditions for more sophisticated logic:
|
| 175 |
```python
|
| 176 |
# Multiple conditions
|
|
@@ -189,13 +229,13 @@ def _(mo):
|
|
| 189 |
return
|
| 190 |
|
| 191 |
|
| 192 |
-
@app.cell
|
| 193 |
def _(humidity, mo, temp, wind):
|
| 194 |
mo.hstack([temp, humidity, wind])
|
| 195 |
return
|
| 196 |
|
| 197 |
|
| 198 |
-
@app.cell
|
| 199 |
def _(mo):
|
| 200 |
temp = mo.ui.number(value=25, start=-20, stop=50, label="Temperature (°C)")
|
| 201 |
humidity = mo.ui.slider(value=60, start=0, stop=100, label="Humidity (%)")
|
|
@@ -203,30 +243,31 @@ def _(mo):
|
|
| 203 |
return humidity, temp, wind
|
| 204 |
|
| 205 |
|
| 206 |
-
@app.cell
|
| 207 |
def _(humidity, mo, temp, wind):
|
| 208 |
def get_weather_advice():
|
| 209 |
conditions = []
|
| 210 |
-
|
| 211 |
if temp.value > 30:
|
| 212 |
conditions.append("🌡️ High temperature")
|
| 213 |
elif temp.value < 10:
|
| 214 |
conditions.append("❄️ Cold temperature")
|
| 215 |
-
|
| 216 |
if humidity.value > 80:
|
| 217 |
conditions.append("💧 High humidity")
|
| 218 |
elif humidity.value < 30:
|
| 219 |
conditions.append("🏜️ Low humidity")
|
| 220 |
-
|
| 221 |
if wind.value > 30:
|
| 222 |
conditions.append("💨 Strong winds")
|
| 223 |
-
|
| 224 |
return conditions
|
| 225 |
-
|
|
|
|
| 226 |
conditions = get_weather_advice()
|
| 227 |
-
|
| 228 |
message = f"""
|
| 229 |
-
### Weather
|
| 230 |
|
| 231 |
Current Conditions:
|
| 232 |
|
|
@@ -236,7 +277,7 @@ def _(humidity, mo, temp, wind):
|
|
| 236 |
|
| 237 |
- Wind Speed: {wind.value} km/h
|
| 238 |
|
| 239 |
-
Alerts: {
|
| 240 |
"""
|
| 241 |
|
| 242 |
mo.md(message)
|
|
@@ -245,22 +286,22 @@ def _(humidity, mo, temp, wind):
|
|
| 245 |
|
| 246 |
@app.cell(hide_code=True)
|
| 247 |
def _(mo):
|
| 248 |
-
|
| 249 |
-
##
|
| 250 |
-
|
| 251 |
-
Next Steps:
|
| 252 |
|
| 253 |
- Practice combining multiple conditions
|
| 254 |
-
|
| 255 |
- Explore nested if statements
|
| 256 |
-
|
| 257 |
-
- Try creating your own complex decision trees (pun on an ML algorithm!)
|
| 258 |
|
| 259 |
Keep coding! 🎯✨
|
| 260 |
""")
|
|
|
|
| 261 |
|
| 262 |
-
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
|
| 266 |
if __name__ == "__main__":
|
|
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
+
__generated_with = "0.10.19"
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
@app.cell(hide_code=True)
|
| 15 |
def _(mo):
|
| 16 |
mo.md(
|
| 17 |
"""
|
| 18 |
+
# 🔄 Conditional logic
|
| 19 |
|
| 20 |
+
This tutorial teaches you how to how to make **decisions** in your code, using
|
| 21 |
+
Python's conditional statements.
|
| 22 |
|
| 23 |
## If Statements
|
| 24 |
The foundation of decision-making in Python:
|
|
|
|
| 36 |
return
|
| 37 |
|
| 38 |
|
| 39 |
+
@app.cell(hide_code=True)
|
| 40 |
+
def _(mo):
|
| 41 |
+
mo.md("""**Try it!** Try changing the value of `42` below, and see how the output changes.""")
|
| 42 |
+
return
|
| 43 |
+
|
| 44 |
+
|
| 45 |
@app.cell
|
| 46 |
def _():
|
| 47 |
number = 42
|
| 48 |
return (number,)
|
| 49 |
|
| 50 |
|
| 51 |
+
@app.cell(hide_code=True)
|
| 52 |
+
def _(mo):
|
| 53 |
+
mo.md(
|
| 54 |
+
r"""
|
| 55 |
+
Compare numbers using operators like
|
| 56 |
+
|
| 57 |
+
- `>`
|
| 58 |
+
- `>=`
|
| 59 |
+
- `<`
|
| 60 |
+
- `<=`
|
| 61 |
+
- `==` (note the two equal signs!)
|
| 62 |
+
"""
|
| 63 |
+
)
|
| 64 |
+
return
|
| 65 |
+
|
| 66 |
+
|
| 67 |
@app.cell
|
| 68 |
+
def _(mo, number):
|
| 69 |
+
if number > 42:
|
| 70 |
+
result = "Greater than 42"
|
| 71 |
elif number == 42:
|
| 72 |
+
result = "Equal to 42!"
|
| 73 |
else:
|
| 74 |
+
result = "Less than 42"
|
| 75 |
+
mo.md(result)
|
| 76 |
return (result,)
|
| 77 |
|
| 78 |
|
|
|
|
| 80 |
def _(mo):
|
| 81 |
mo.md(
|
| 82 |
r"""
|
| 83 |
+
### Interactive decision making
|
| 84 |
+
**Try it!** Try changing the conditions below and see how the results change:
|
| 85 |
"""
|
| 86 |
)
|
| 87 |
return
|
| 88 |
|
| 89 |
|
| 90 |
+
@app.cell(hide_code=True)
|
| 91 |
def _(mo, threshold, value):
|
| 92 |
+
mo.hstack([value, threshold], justify="start")
|
| 93 |
return
|
| 94 |
|
| 95 |
|
| 96 |
+
@app.cell(hide_code=True)
|
| 97 |
def _(mo):
|
| 98 |
value = mo.ui.number(value=25, start=0, stop=100, label="Enter a number")
|
| 99 |
threshold = mo.ui.slider(value=50, start=0, stop=100, label="Set threshold")
|
| 100 |
return threshold, value
|
| 101 |
|
| 102 |
|
| 103 |
+
@app.cell(hide_code=True)
|
| 104 |
def _(mo, threshold, value):
|
| 105 |
if value.value > threshold.value:
|
| 106 |
decision = f"{value.value} is greater than {threshold.value}"
|
|
|
|
| 112 |
mo.hstack(
|
| 113 |
[
|
| 114 |
mo.md(f"**Decision**: {decision}"),
|
| 115 |
+
mo.md(
|
| 116 |
+
f"**Threshold cleared?**: {'✅' if value.value >= threshold.value else '❌'}"
|
| 117 |
+
),
|
| 118 |
],
|
| 119 |
+
justify="space-around",
|
| 120 |
)
|
| 121 |
return (decision,)
|
| 122 |
|
|
|
|
| 125 |
def _(mo):
|
| 126 |
mo.md(
|
| 127 |
r"""
|
| 128 |
+
## Boolean operations
|
| 129 |
Python uses boolean operators to combine conditions:
|
| 130 |
|
| 131 |
- `and`: Both conditions must be True
|
|
|
|
| 138 |
return
|
| 139 |
|
| 140 |
|
| 141 |
+
@app.cell(hide_code=True)
|
| 142 |
+
def _(mo):
|
| 143 |
+
_text = mo.md("""
|
| 144 |
+
- Try different combinations of age and ID status
|
| 145 |
+
- Notice how both conditions must be True to allow voting
|
| 146 |
+
- Experiment with edge cases (exactly 18, no ID, etc.)
|
| 147 |
+
""")
|
| 148 |
+
mo.accordion({"💡 Experiment Tips": _text})
|
| 149 |
+
return
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@app.cell(hide_code=True)
|
| 153 |
def _(age, has_id, mo):
|
| 154 |
+
mo.hstack([age, has_id], justify="start")
|
| 155 |
return
|
| 156 |
|
| 157 |
|
| 158 |
+
@app.cell(hide_code=True)
|
| 159 |
def _(mo):
|
| 160 |
age = mo.ui.number(value=18, start=0, stop=120, label="Age")
|
| 161 |
has_id = mo.ui.switch(value=True, label="Has ID")
|
| 162 |
return age, has_id
|
| 163 |
|
| 164 |
|
| 165 |
+
@app.cell(hide_code=True)
|
| 166 |
def _(age, has_id, mo):
|
| 167 |
can_vote = age.value >= 18 and has_id.value
|
| 168 |
|
| 169 |
explanation = f"""
|
| 170 |
+
### Voting eligibility check
|
| 171 |
|
| 172 |
Current Status:
|
| 173 |
|
| 174 |
- Age: {age.value} years old
|
| 175 |
|
| 176 |
+
- Has ID: {"Yes" if has_id.value else "No"}
|
| 177 |
|
| 178 |
+
- Can Vote: {"Yes ✅" if can_vote else "No ❌"}
|
| 179 |
|
| 180 |
+
Reason: {
|
| 181 |
+
"Both age and ID requirements met"
|
| 182 |
+
if can_vote
|
| 183 |
+
else "Missing " + ("required age" if age.value < 18 else "valid ID")
|
| 184 |
+
}
|
| 185 |
"""
|
| 186 |
|
| 187 |
mo.md(explanation)
|
|
|
|
| 190 |
|
| 191 |
@app.cell(hide_code=True)
|
| 192 |
def _(mo):
|
| 193 |
+
mo.md(r"""**Try it!** Write Python code that computes whether an individual can vote.""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
return
|
| 195 |
|
| 196 |
|
| 197 |
+
@app.cell
|
| 198 |
+
def _():
|
| 199 |
+
my_age = 18
|
| 200 |
+
return (my_age,)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
@app.cell
|
| 204 |
+
def _():
|
| 205 |
+
has_an_id = False
|
| 206 |
+
return (has_an_id,)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
@app.cell(hide_code=True)
|
| 210 |
def _(mo):
|
| 211 |
mo.md(
|
| 212 |
"""
|
| 213 |
+
## Complex conditions
|
| 214 |
Combine multiple conditions for more sophisticated logic:
|
| 215 |
```python
|
| 216 |
# Multiple conditions
|
|
|
|
| 229 |
return
|
| 230 |
|
| 231 |
|
| 232 |
+
@app.cell(hide_code=True)
|
| 233 |
def _(humidity, mo, temp, wind):
|
| 234 |
mo.hstack([temp, humidity, wind])
|
| 235 |
return
|
| 236 |
|
| 237 |
|
| 238 |
+
@app.cell(hide_code=True)
|
| 239 |
def _(mo):
|
| 240 |
temp = mo.ui.number(value=25, start=-20, stop=50, label="Temperature (°C)")
|
| 241 |
humidity = mo.ui.slider(value=60, start=0, stop=100, label="Humidity (%)")
|
|
|
|
| 243 |
return humidity, temp, wind
|
| 244 |
|
| 245 |
|
| 246 |
+
@app.cell(hide_code=True)
|
| 247 |
def _(humidity, mo, temp, wind):
|
| 248 |
def get_weather_advice():
|
| 249 |
conditions = []
|
| 250 |
+
|
| 251 |
if temp.value > 30:
|
| 252 |
conditions.append("🌡️ High temperature")
|
| 253 |
elif temp.value < 10:
|
| 254 |
conditions.append("❄️ Cold temperature")
|
| 255 |
+
|
| 256 |
if humidity.value > 80:
|
| 257 |
conditions.append("💧 High humidity")
|
| 258 |
elif humidity.value < 30:
|
| 259 |
conditions.append("🏜️ Low humidity")
|
| 260 |
+
|
| 261 |
if wind.value > 30:
|
| 262 |
conditions.append("💨 Strong winds")
|
| 263 |
+
|
| 264 |
return conditions
|
| 265 |
+
|
| 266 |
+
|
| 267 |
conditions = get_weather_advice()
|
| 268 |
+
|
| 269 |
message = f"""
|
| 270 |
+
### Weather analysis
|
| 271 |
|
| 272 |
Current Conditions:
|
| 273 |
|
|
|
|
| 277 |
|
| 278 |
- Wind Speed: {wind.value} km/h
|
| 279 |
|
| 280 |
+
Alerts: {", ".join(conditions) if conditions else "No special alerts"}
|
| 281 |
"""
|
| 282 |
|
| 283 |
mo.md(message)
|
|
|
|
| 286 |
|
| 287 |
@app.cell(hide_code=True)
|
| 288 |
def _(mo):
|
| 289 |
+
mo.md("""
|
| 290 |
+
## Next steps
|
|
|
|
|
|
|
| 291 |
|
| 292 |
- Practice combining multiple conditions
|
|
|
|
| 293 |
- Explore nested if statements
|
| 294 |
+
- Try creating your own complex decision trees
|
|
|
|
| 295 |
|
| 296 |
Keep coding! 🎯✨
|
| 297 |
""")
|
| 298 |
+
return
|
| 299 |
|
| 300 |
+
|
| 301 |
+
@app.cell
|
| 302 |
+
def _():
|
| 303 |
+
import marimo as mo
|
| 304 |
+
return (mo,)
|
| 305 |
|
| 306 |
|
| 307 |
if __name__ == "__main__":
|
Python/phase_2/loop_structures.py → python/005_loops.py
RENAMED
|
@@ -7,38 +7,32 @@
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
-
__generated_with = "0.10.
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
| 14 |
-
@app.cell
|
| 15 |
-
def _():
|
| 16 |
-
import marimo as mo
|
| 17 |
-
return (mo,)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
@app.cell(hide_code=True)
|
| 21 |
def _(mo):
|
| 22 |
mo.md(
|
| 23 |
"""
|
| 24 |
-
# 🔄 Loops
|
| 25 |
|
| 26 |
-
Let's
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
|
| 31 |
```python
|
| 32 |
-
# For loop
|
| 33 |
for i in range(5):
|
| 34 |
print(i)
|
| 35 |
|
| 36 |
-
# While loop
|
| 37 |
while condition:
|
| 38 |
do_something()
|
| 39 |
```
|
| 40 |
|
| 41 |
-
Let's start with a simple list to explore loops.
|
| 42 |
"""
|
| 43 |
)
|
| 44 |
return
|
|
@@ -54,7 +48,7 @@ def _():
|
|
| 54 |
def _(mo):
|
| 55 |
mo.md(
|
| 56 |
"""
|
| 57 |
-
##
|
| 58 |
|
| 59 |
The for loop is perfect for iterating over sequences.
|
| 60 |
Try changing the `sample_fruits` list above and see how the output changes.
|
|
@@ -65,122 +59,128 @@ def _(mo):
|
|
| 65 |
|
| 66 |
@app.cell
|
| 67 |
def _(sample_fruits):
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
print(f"I like {_fruit}s!")
|
| 71 |
-
_print_fruits()
|
| 72 |
return
|
| 73 |
|
| 74 |
|
| 75 |
@app.cell(hide_code=True)
|
| 76 |
def _(mo):
|
| 77 |
-
mo.md(
|
| 78 |
-
|
|
|
|
| 79 |
|
| 80 |
-
When you need both the item and its position, use enumerate()
|
| 81 |
-
"""
|
|
|
|
| 82 |
return
|
| 83 |
|
| 84 |
|
| 85 |
@app.cell
|
| 86 |
def _(sample_fruits):
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
print(f"{_idx + 1}. {_fruit}")
|
| 90 |
-
_print_enumerated()
|
| 91 |
return
|
| 92 |
|
| 93 |
|
| 94 |
@app.cell(hide_code=True)
|
| 95 |
def _(mo):
|
| 96 |
-
mo.md(
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
return
|
| 102 |
|
| 103 |
|
| 104 |
@app.cell
|
| 105 |
def _():
|
| 106 |
-
|
| 107 |
-
print(
|
| 108 |
-
print("range(2, 5):", list(range(2, 5)))
|
| 109 |
-
print("range(0, 10, 2):", list(range(0, 10, 2)))
|
| 110 |
-
_demonstrate_range()
|
| 111 |
return
|
| 112 |
|
| 113 |
|
| 114 |
@app.cell(hide_code=True)
|
| 115 |
def _(mo):
|
| 116 |
-
mo.md(
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
|
|
|
|
|
|
|
| 119 |
return
|
| 120 |
|
| 121 |
|
| 122 |
@app.cell
|
| 123 |
def _():
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
_count += 1
|
| 129 |
-
_count_up()
|
| 130 |
return
|
| 131 |
|
| 132 |
|
| 133 |
@app.cell(hide_code=True)
|
| 134 |
def _(mo):
|
| 135 |
-
mo.md(
|
| 136 |
-
|
|
|
|
| 137 |
|
| 138 |
Python provides several ways to control loop execution:
|
| 139 |
|
| 140 |
-
- `break`:
|
| 141 |
|
| 142 |
-
- `continue`:
|
| 143 |
|
| 144 |
-
|
| 145 |
-
"""
|
|
|
|
| 146 |
return
|
| 147 |
|
| 148 |
|
| 149 |
@app.cell
|
| 150 |
def _():
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
print("Loop ended early!")
|
| 157 |
-
_demonstrate_break()
|
| 158 |
return
|
| 159 |
|
| 160 |
|
| 161 |
@app.cell
|
| 162 |
def _():
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
print(_i)
|
| 168 |
-
_demonstrate_continue()
|
| 169 |
return
|
| 170 |
|
| 171 |
|
| 172 |
@app.cell(hide_code=True)
|
| 173 |
def _(mo):
|
| 174 |
-
mo.md(
|
| 175 |
-
|
|
|
|
| 176 |
|
| 177 |
Here are some common patterns you'll use with loops:
|
| 178 |
|
| 179 |
```python
|
| 180 |
# Pattern 1: Accumulator
|
| 181 |
-
|
| 182 |
for num in [1, 2, 3, 4, 5]:
|
| 183 |
-
|
| 184 |
|
| 185 |
# Pattern 2: Search
|
| 186 |
found = False
|
|
@@ -195,26 +195,27 @@ def _(mo):
|
|
| 195 |
if condition:
|
| 196 |
filtered.append(item)
|
| 197 |
```
|
| 198 |
-
"""
|
|
|
|
| 199 |
return
|
| 200 |
|
| 201 |
|
| 202 |
@app.cell(hide_code=True)
|
| 203 |
def _(mo):
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
Next Steps:
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
|
|
|
| 212 |
|
| 213 |
-
Keep iterating! 🔄✨
|
| 214 |
-
""")
|
| 215 |
|
| 216 |
-
|
| 217 |
-
|
|
|
|
|
|
|
| 218 |
|
| 219 |
|
| 220 |
if __name__ == "__main__":
|
|
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
+
__generated_with = "0.10.19"
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
@app.cell(hide_code=True)
|
| 15 |
def _(mo):
|
| 16 |
mo.md(
|
| 17 |
"""
|
| 18 |
+
# 🔄 Loops
|
| 19 |
|
| 20 |
+
Let's learn how Python helps us repeat tasks efficiently with loops.
|
| 21 |
|
| 22 |
+
A "loop" is a way to execute a block of code multiple times. Python has two
|
| 23 |
+
main types of loops:
|
| 24 |
|
| 25 |
```python
|
| 26 |
+
# For loop: when you know how many times to repeat
|
| 27 |
for i in range(5):
|
| 28 |
print(i)
|
| 29 |
|
| 30 |
+
# While loop: when you don't know how many repetitions
|
| 31 |
while condition:
|
| 32 |
do_something()
|
| 33 |
```
|
| 34 |
|
| 35 |
+
Let's start with a simple list to explore loops. Feel free to modify this list and see how the subsequent outputs change.
|
| 36 |
"""
|
| 37 |
)
|
| 38 |
return
|
|
|
|
| 48 |
def _(mo):
|
| 49 |
mo.md(
|
| 50 |
"""
|
| 51 |
+
## The for loop
|
| 52 |
|
| 53 |
The for loop is perfect for iterating over sequences.
|
| 54 |
Try changing the `sample_fruits` list above and see how the output changes.
|
|
|
|
| 59 |
|
| 60 |
@app.cell
|
| 61 |
def _(sample_fruits):
|
| 62 |
+
for _fruit in sample_fruits:
|
| 63 |
+
print(f"I like {_fruit}s!")
|
|
|
|
|
|
|
| 64 |
return
|
| 65 |
|
| 66 |
|
| 67 |
@app.cell(hide_code=True)
|
| 68 |
def _(mo):
|
| 69 |
+
mo.md(
|
| 70 |
+
"""
|
| 71 |
+
### Getting the position of an item
|
| 72 |
|
| 73 |
+
When you need both the item and its position, use `enumerate()`:
|
| 74 |
+
"""
|
| 75 |
+
)
|
| 76 |
return
|
| 77 |
|
| 78 |
|
| 79 |
@app.cell
|
| 80 |
def _(sample_fruits):
|
| 81 |
+
for _idx, _fruit in enumerate(sample_fruits):
|
| 82 |
+
print(f"{_idx + 1}. {_fruit}")
|
|
|
|
|
|
|
| 83 |
return
|
| 84 |
|
| 85 |
|
| 86 |
@app.cell(hide_code=True)
|
| 87 |
def _(mo):
|
| 88 |
+
mo.md(
|
| 89 |
+
"""
|
| 90 |
+
### Iterating over a range of numbers
|
| 91 |
+
|
| 92 |
+
`range()` is a powerful function for generating sequences of numbers:
|
| 93 |
+
"""
|
| 94 |
+
)
|
| 95 |
+
return
|
| 96 |
|
| 97 |
+
|
| 98 |
+
@app.cell
|
| 99 |
+
def _():
|
| 100 |
+
print("range(5):", list(range(5)))
|
| 101 |
+
print("range(2, 5):", list(range(2, 5)))
|
| 102 |
+
print("range(0, 10, 2):", list(range(0, 10, 2)))
|
| 103 |
return
|
| 104 |
|
| 105 |
|
| 106 |
@app.cell
|
| 107 |
def _():
|
| 108 |
+
for _i in range(5):
|
| 109 |
+
print(_i)
|
|
|
|
|
|
|
|
|
|
| 110 |
return
|
| 111 |
|
| 112 |
|
| 113 |
@app.cell(hide_code=True)
|
| 114 |
def _(mo):
|
| 115 |
+
mo.md(
|
| 116 |
+
"""
|
| 117 |
+
## The `while` loop
|
| 118 |
|
| 119 |
+
While loops continue as long as a condition is `True`.
|
| 120 |
+
"""
|
| 121 |
+
)
|
| 122 |
return
|
| 123 |
|
| 124 |
|
| 125 |
@app.cell
|
| 126 |
def _():
|
| 127 |
+
_count = 0
|
| 128 |
+
while _count < 5:
|
| 129 |
+
print(f"The count is {_count}")
|
| 130 |
+
_count += 1
|
|
|
|
|
|
|
| 131 |
return
|
| 132 |
|
| 133 |
|
| 134 |
@app.cell(hide_code=True)
|
| 135 |
def _(mo):
|
| 136 |
+
mo.md(
|
| 137 |
+
"""
|
| 138 |
+
## Controlling loop execution
|
| 139 |
|
| 140 |
Python provides several ways to control loop execution:
|
| 141 |
|
| 142 |
+
- `break`: exit the loop immediately
|
| 143 |
|
| 144 |
+
- `continue`: skip to the next iteration
|
| 145 |
|
| 146 |
+
These can be used with both `for` and `while` loops.
|
| 147 |
+
"""
|
| 148 |
+
)
|
| 149 |
return
|
| 150 |
|
| 151 |
|
| 152 |
@app.cell
|
| 153 |
def _():
|
| 154 |
+
for _i in range(1, 6):
|
| 155 |
+
if _i == 4:
|
| 156 |
+
print("Breaking out of the loop.")
|
| 157 |
+
break
|
| 158 |
+
print(_i)
|
|
|
|
|
|
|
| 159 |
return
|
| 160 |
|
| 161 |
|
| 162 |
@app.cell
|
| 163 |
def _():
|
| 164 |
+
for _i in range(1, 6):
|
| 165 |
+
if _i == 3:
|
| 166 |
+
continue
|
| 167 |
+
print(_i)
|
|
|
|
|
|
|
| 168 |
return
|
| 169 |
|
| 170 |
|
| 171 |
@app.cell(hide_code=True)
|
| 172 |
def _(mo):
|
| 173 |
+
mo.md(
|
| 174 |
+
"""
|
| 175 |
+
## Practical loop patterns
|
| 176 |
|
| 177 |
Here are some common patterns you'll use with loops:
|
| 178 |
|
| 179 |
```python
|
| 180 |
# Pattern 1: Accumulator
|
| 181 |
+
value = 0
|
| 182 |
for num in [1, 2, 3, 4, 5]:
|
| 183 |
+
value += num
|
| 184 |
|
| 185 |
# Pattern 2: Search
|
| 186 |
found = False
|
|
|
|
| 195 |
if condition:
|
| 196 |
filtered.append(item)
|
| 197 |
```
|
| 198 |
+
"""
|
| 199 |
+
)
|
| 200 |
return
|
| 201 |
|
| 202 |
|
| 203 |
@app.cell(hide_code=True)
|
| 204 |
def _(mo):
|
| 205 |
+
mo.md(
|
| 206 |
+
r"""
|
| 207 |
+
## Next steps
|
|
|
|
| 208 |
|
| 209 |
+
Check out the official [Python docs on loops and control flow](https://docs.python.org/3/tutorial/controlflow.html).
|
| 210 |
+
"""
|
| 211 |
+
)
|
| 212 |
+
return
|
| 213 |
|
|
|
|
|
|
|
| 214 |
|
| 215 |
+
@app.cell
|
| 216 |
+
def _():
|
| 217 |
+
import marimo as mo
|
| 218 |
+
return (mo,)
|
| 219 |
|
| 220 |
|
| 221 |
if __name__ == "__main__":
|
Python/phase_3/dictionaries.py → python/006_dictionaries.py
RENAMED
|
@@ -7,31 +7,25 @@
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
-
__generated_with = "0.10.
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
| 14 |
-
@app.cell
|
| 15 |
-
def _():
|
| 16 |
-
import marimo as mo
|
| 17 |
-
return (mo,)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
@app.cell(hide_code=True)
|
| 21 |
def _(mo):
|
| 22 |
mo.md(
|
| 23 |
"""
|
| 24 |
-
# 📚
|
| 25 |
|
| 26 |
-
|
| 27 |
|
| 28 |
-
## Creating
|
| 29 |
-
|
| 30 |
|
| 31 |
```python
|
| 32 |
-
simple_dict = {"name": "Alice", "age": 25}
|
| 33 |
-
empty_dict = dict()
|
| 34 |
-
from_pairs = dict([("a", 1), ("b", 2)])
|
| 35 |
```
|
| 36 |
|
| 37 |
Below is a sample dictionary we'll use to explore operations.
|
|
@@ -47,7 +41,7 @@ def _():
|
|
| 47 |
"type": "programming language",
|
| 48 |
"year": 1991,
|
| 49 |
"creator": "Guido van Rossum",
|
| 50 |
-
"is_awesome": True
|
| 51 |
}
|
| 52 |
return (sample_dict,)
|
| 53 |
|
|
@@ -56,10 +50,23 @@ def _():
|
|
| 56 |
def _(mo):
|
| 57 |
mo.md(
|
| 58 |
"""
|
| 59 |
-
##
|
| 60 |
|
| 61 |
Let's explore how to work with dictionaries.
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
"""
|
| 64 |
)
|
| 65 |
return
|
|
@@ -67,48 +74,54 @@ def _(mo):
|
|
| 67 |
|
| 68 |
@app.cell
|
| 69 |
def _(sample_dict):
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
@app.cell
|
| 79 |
def _(sample_dict):
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
print(f"Version: {sample_dict.get('version', 'Not specified')}")
|
| 83 |
-
print(f"Type: {sample_dict.get('type', 'Unknown')}")
|
| 84 |
-
safe_access()
|
| 85 |
-
return (safe_access,)
|
| 86 |
|
| 87 |
|
| 88 |
@app.cell(hide_code=True)
|
| 89 |
def _(mo):
|
| 90 |
-
mo.md(
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
|
|
|
| 95 |
return
|
| 96 |
|
| 97 |
|
| 98 |
@app.cell
|
| 99 |
def _(sample_dict):
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
| 107 |
|
| 108 |
|
| 109 |
@app.cell
|
| 110 |
def _():
|
| 111 |
-
# Modifying dictionaries
|
| 112 |
def demonstrate_modification():
|
| 113 |
_dict = {"a": 1, "b": 2}
|
| 114 |
print("Original:", _dict)
|
|
@@ -120,42 +133,45 @@ def _():
|
|
| 120 |
# Removing
|
| 121 |
_removed = _dict.pop("b")
|
| 122 |
print(f"Removed {_removed}, Now:", _dict)
|
|
|
|
|
|
|
| 123 |
demonstrate_modification()
|
| 124 |
return (demonstrate_modification,)
|
| 125 |
|
| 126 |
|
| 127 |
@app.cell(hide_code=True)
|
| 128 |
def _(mo):
|
| 129 |
-
mo.md(
|
| 130 |
-
|
|
|
|
| 131 |
|
| 132 |
Create dictionaries efficiently with dictionary comprehensions:
|
| 133 |
-
"""
|
|
|
|
| 134 |
return
|
| 135 |
|
| 136 |
|
| 137 |
@app.cell
|
| 138 |
def _():
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
_squares = {x: x**2 for x in range(5)}
|
| 143 |
-
print("Squares:", _squares)
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
return (demonstrate_comprehension,)
|
| 150 |
|
| 151 |
|
| 152 |
@app.cell(hide_code=True)
|
| 153 |
def _(mo):
|
| 154 |
-
mo.md(
|
| 155 |
-
|
|
|
|
| 156 |
|
| 157 |
Dictionaries can contain other dictionaries, creating complex data structures:
|
| 158 |
-
"""
|
|
|
|
| 159 |
return
|
| 160 |
|
| 161 |
|
|
@@ -166,45 +182,35 @@ def _():
|
|
| 166 |
"alice": {
|
| 167 |
"age": 25,
|
| 168 |
"email": "alice@example.com",
|
| 169 |
-
"interests": ["python", "data science"]
|
| 170 |
},
|
| 171 |
"bob": {
|
| 172 |
"age": 30,
|
| 173 |
"email": "bob@example.com",
|
| 174 |
-
"interests": ["web dev", "gaming"]
|
| 175 |
-
}
|
| 176 |
}
|
| 177 |
}
|
| 178 |
return (nested_data,)
|
| 179 |
|
| 180 |
|
| 181 |
@app.cell
|
| 182 |
-
def _(nested_data):
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
for _key in keys:
|
| 192 |
-
if isinstance(_current, dict):
|
| 193 |
-
_current = _current.get(_key, default)
|
| 194 |
-
else:
|
| 195 |
-
return default
|
| 196 |
-
return _current
|
| 197 |
-
|
| 198 |
-
print("\nSafe access example:")
|
| 199 |
-
print("Charlie's age:", _get_nested(nested_data, "users", "charlie", "age", default="Not found"))
|
| 200 |
-
access_nested()
|
| 201 |
-
return (access_nested,)
|
| 202 |
|
| 203 |
|
| 204 |
@app.cell(hide_code=True)
|
| 205 |
def _(mo):
|
| 206 |
-
mo.md(
|
| 207 |
-
|
|
|
|
| 208 |
|
| 209 |
Here are some useful patterns when working with dictionaries:
|
| 210 |
|
|
@@ -227,27 +233,15 @@ def _(mo):
|
|
| 227 |
cache[arg] = compute_result(arg)
|
| 228 |
return cache[arg]
|
| 229 |
```
|
| 230 |
-
"""
|
|
|
|
| 231 |
return
|
| 232 |
|
| 233 |
|
| 234 |
-
@app.cell
|
| 235 |
-
def _(
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
Next Steps:
|
| 240 |
-
|
| 241 |
-
- Practice different dictionary methods
|
| 242 |
-
- Try creating nested data structures
|
| 243 |
-
- Experiment with dictionary comprehensions
|
| 244 |
-
- Build something using common patterns
|
| 245 |
-
|
| 246 |
-
Keep organizing your data! 🗂️✨
|
| 247 |
-
""")
|
| 248 |
-
|
| 249 |
-
mo.callout(callout_text, kind="success")
|
| 250 |
-
return (callout_text,)
|
| 251 |
|
| 252 |
|
| 253 |
if __name__ == "__main__":
|
|
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
+
__generated_with = "0.10.19"
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
@app.cell(hide_code=True)
|
| 15 |
def _(mo):
|
| 16 |
mo.md(
|
| 17 |
"""
|
| 18 |
+
# 📚 Dictionaries
|
| 19 |
|
| 20 |
+
Dictionaries are collections of key-value pairs, with each key associated with a value. The keys are unique, meaning they show up only once.
|
| 21 |
|
| 22 |
+
## Creating dictionaries
|
| 23 |
+
Here are a few ways to create dictionaries:
|
| 24 |
|
| 25 |
```python
|
| 26 |
+
simple_dict = {"name": "Alice", "age": 25}
|
| 27 |
+
empty_dict = dict()
|
| 28 |
+
from_pairs = dict([("a", 1), ("b", 2)])
|
| 29 |
```
|
| 30 |
|
| 31 |
Below is a sample dictionary we'll use to explore operations.
|
|
|
|
| 41 |
"type": "programming language",
|
| 42 |
"year": 1991,
|
| 43 |
"creator": "Guido van Rossum",
|
| 44 |
+
"is_awesome": True,
|
| 45 |
}
|
| 46 |
return (sample_dict,)
|
| 47 |
|
|
|
|
| 50 |
def _(mo):
|
| 51 |
mo.md(
|
| 52 |
"""
|
| 53 |
+
## Operations
|
| 54 |
|
| 55 |
Let's explore how to work with dictionaries.
|
| 56 |
+
|
| 57 |
+
**Try it!** Try modifying the `sample_dict` above and watch how the results change!
|
| 58 |
+
"""
|
| 59 |
+
)
|
| 60 |
+
return
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@app.cell(hide_code=True)
|
| 64 |
+
def _(mo):
|
| 65 |
+
mo.md(
|
| 66 |
+
r"""
|
| 67 |
+
### Accessing values by key
|
| 68 |
+
|
| 69 |
+
Access values by key using square brackets, like below
|
| 70 |
"""
|
| 71 |
)
|
| 72 |
return
|
|
|
|
| 74 |
|
| 75 |
@app.cell
|
| 76 |
def _(sample_dict):
|
| 77 |
+
sample_dict['name'], sample_dict['year']
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@app.cell(hide_code=True)
|
| 82 |
+
def _(mo):
|
| 83 |
+
mo.md(r"""If you're not sure if a dictionary has a given key, use `get()`:""")
|
| 84 |
+
return
|
| 85 |
|
| 86 |
|
| 87 |
@app.cell
|
| 88 |
def _(sample_dict):
|
| 89 |
+
sample_dict.get("version", "Not specified"), sample_dict.get("type", "Unknown")
|
| 90 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
|
| 93 |
@app.cell(hide_code=True)
|
| 94 |
def _(mo):
|
| 95 |
+
mo.md(
|
| 96 |
+
"""
|
| 97 |
+
## Enumerating dictionary contents
|
| 98 |
+
|
| 99 |
+
Python dictionaries come with helpful methods to enumerate keys, values, and pairs.
|
| 100 |
+
"""
|
| 101 |
+
)
|
| 102 |
+
return
|
| 103 |
+
|
| 104 |
|
| 105 |
+
@app.cell
|
| 106 |
+
def _(sample_dict):
|
| 107 |
+
print(list(sample_dict.keys()))
|
| 108 |
return
|
| 109 |
|
| 110 |
|
| 111 |
@app.cell
|
| 112 |
def _(sample_dict):
|
| 113 |
+
print(list(sample_dict.values()))
|
| 114 |
+
return
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@app.cell
|
| 118 |
+
def _(sample_dict):
|
| 119 |
+
print(list(sample_dict.items()))
|
| 120 |
+
return
|
| 121 |
|
| 122 |
|
| 123 |
@app.cell
|
| 124 |
def _():
|
|
|
|
| 125 |
def demonstrate_modification():
|
| 126 |
_dict = {"a": 1, "b": 2}
|
| 127 |
print("Original:", _dict)
|
|
|
|
| 133 |
# Removing
|
| 134 |
_removed = _dict.pop("b")
|
| 135 |
print(f"Removed {_removed}, Now:", _dict)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
demonstrate_modification()
|
| 139 |
return (demonstrate_modification,)
|
| 140 |
|
| 141 |
|
| 142 |
@app.cell(hide_code=True)
|
| 143 |
def _(mo):
|
| 144 |
+
mo.md(
|
| 145 |
+
"""
|
| 146 |
+
## Dictionary comprehension
|
| 147 |
|
| 148 |
Create dictionaries efficiently with dictionary comprehensions:
|
| 149 |
+
"""
|
| 150 |
+
)
|
| 151 |
return
|
| 152 |
|
| 153 |
|
| 154 |
@app.cell
|
| 155 |
def _():
|
| 156 |
+
print({x: x**2 for x in range(5)})
|
| 157 |
+
return
|
| 158 |
+
|
|
|
|
|
|
|
| 159 |
|
| 160 |
+
@app.cell
|
| 161 |
+
def _():
|
| 162 |
+
print({x: x**2 for x in range(5) if x % 2 == 0})
|
| 163 |
+
return
|
|
|
|
| 164 |
|
| 165 |
|
| 166 |
@app.cell(hide_code=True)
|
| 167 |
def _(mo):
|
| 168 |
+
mo.md(
|
| 169 |
+
"""
|
| 170 |
+
## Nested dictionaries
|
| 171 |
|
| 172 |
Dictionaries can contain other dictionaries, creating complex data structures:
|
| 173 |
+
"""
|
| 174 |
+
)
|
| 175 |
return
|
| 176 |
|
| 177 |
|
|
|
|
| 182 |
"alice": {
|
| 183 |
"age": 25,
|
| 184 |
"email": "alice@example.com",
|
| 185 |
+
"interests": ["python", "data science"],
|
| 186 |
},
|
| 187 |
"bob": {
|
| 188 |
"age": 30,
|
| 189 |
"email": "bob@example.com",
|
| 190 |
+
"interests": ["web dev", "gaming"],
|
| 191 |
+
},
|
| 192 |
}
|
| 193 |
}
|
| 194 |
return (nested_data,)
|
| 195 |
|
| 196 |
|
| 197 |
@app.cell
|
| 198 |
+
def _(mo, nested_data):
|
| 199 |
+
mo.md(f"Alice's age: {nested_data["users"]["alice"]["age"]}")
|
| 200 |
+
return
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
@app.cell
|
| 204 |
+
def _(mo, nested_data):
|
| 205 |
+
mo.md(f"Bob's interests: {nested_data["users"]["bob"]["interests"]}")
|
| 206 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
|
| 209 |
@app.cell(hide_code=True)
|
| 210 |
def _(mo):
|
| 211 |
+
mo.md(
|
| 212 |
+
"""
|
| 213 |
+
## Common dictionary patterns
|
| 214 |
|
| 215 |
Here are some useful patterns when working with dictionaries:
|
| 216 |
|
|
|
|
| 233 |
cache[arg] = compute_result(arg)
|
| 234 |
return cache[arg]
|
| 235 |
```
|
| 236 |
+
"""
|
| 237 |
+
)
|
| 238 |
return
|
| 239 |
|
| 240 |
|
| 241 |
+
@app.cell
|
| 242 |
+
def _():
|
| 243 |
+
import marimo as mo
|
| 244 |
+
return (mo,)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
|
| 247 |
if __name__ == "__main__":
|
Python/phase_3/advanced_collections.py → python/007_advanced_collections.py
RENAMED
|
@@ -7,27 +7,22 @@
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
-
__generated_with = "0.10.
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
| 14 |
-
@app.cell
|
| 15 |
-
def _():
|
| 16 |
-
import marimo as mo
|
| 17 |
-
return (mo,)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
@app.cell(hide_code=True)
|
| 21 |
def _(mo):
|
| 22 |
mo.md(
|
| 23 |
"""
|
| 24 |
-
# 🔄 Advanced
|
| 25 |
|
| 26 |
-
|
| 27 |
|
| 28 |
-
## Lists of
|
| 29 |
-
|
| 30 |
-
|
|
|
|
| 31 |
"""
|
| 32 |
)
|
| 33 |
return
|
|
@@ -48,10 +43,10 @@ def _():
|
|
| 48 |
def _(mo):
|
| 49 |
mo.md(
|
| 50 |
"""
|
| 51 |
-
## Working with Lists of Dictionaries
|
| 52 |
-
|
| 53 |
Let's explore common operations on structured data.
|
| 54 |
-
|
|
|
|
|
|
|
| 55 |
"""
|
| 56 |
)
|
| 57 |
return
|
|
@@ -60,18 +55,22 @@ def _(mo):
|
|
| 60 |
@app.cell
|
| 61 |
def _(users_data):
|
| 62 |
# Finding users with specific skills
|
| 63 |
-
python_users = [
|
|
|
|
|
|
|
| 64 |
print("Python developers:", python_users)
|
| 65 |
return (python_users,)
|
| 66 |
|
| 67 |
|
| 68 |
@app.cell(hide_code=True)
|
| 69 |
def _(mo):
|
| 70 |
-
mo.md(
|
| 71 |
-
|
|
|
|
| 72 |
|
| 73 |
Python collections can be nested in various ways to represent complex data:
|
| 74 |
-
"""
|
|
|
|
| 75 |
return
|
| 76 |
|
| 77 |
|
|
@@ -110,11 +109,13 @@ def _(project_data):
|
|
| 110 |
|
| 111 |
@app.cell(hide_code=True)
|
| 112 |
def _(mo):
|
| 113 |
-
mo.md(
|
| 114 |
-
|
|
|
|
| 115 |
|
| 116 |
Let's explore how to transform and reshape collection data:
|
| 117 |
-
"""
|
|
|
|
| 118 |
return
|
| 119 |
|
| 120 |
|
|
@@ -148,10 +149,11 @@ def _(sales_data):
|
|
| 148 |
|
| 149 |
@app.cell(hide_code=True)
|
| 150 |
def _(mo):
|
| 151 |
-
mo.md(
|
| 152 |
-
|
|
|
|
| 153 |
|
| 154 |
-
Python's collections module provides specialized container datatypes:
|
| 155 |
|
| 156 |
```python
|
| 157 |
from collections import defaultdict, Counter, deque
|
|
@@ -169,7 +171,8 @@ def _(mo):
|
|
| 169 |
history = deque(maxlen=10) # Only keeps last 10 items
|
| 170 |
history.append(item)
|
| 171 |
```
|
| 172 |
-
"""
|
|
|
|
| 173 |
return
|
| 174 |
|
| 175 |
|
|
@@ -191,20 +194,21 @@ def _():
|
|
| 191 |
|
| 192 |
@app.cell(hide_code=True)
|
| 193 |
def _(mo):
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
Next Steps:
|
| 198 |
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
| 202 |
|
| 203 |
-
Keep organizing! 📊✨
|
| 204 |
-
""")
|
| 205 |
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
| 208 |
|
| 209 |
|
| 210 |
if __name__ == "__main__":
|
|
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
+
__generated_with = "0.10.19"
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
@app.cell(hide_code=True)
|
| 15 |
def _(mo):
|
| 16 |
mo.md(
|
| 17 |
"""
|
| 18 |
+
# 🔄 Advanced collections
|
| 19 |
|
| 20 |
+
This tutorials hows advanced patterns for working with collections.
|
| 21 |
|
| 22 |
+
## Lists of dictionaries
|
| 23 |
+
|
| 24 |
+
A common pattern in data handling is working with lists of dictionaries:
|
| 25 |
+
this is helpful for representing structured data like records or entries.
|
| 26 |
"""
|
| 27 |
)
|
| 28 |
return
|
|
|
|
| 43 |
def _(mo):
|
| 44 |
mo.md(
|
| 45 |
"""
|
|
|
|
|
|
|
| 46 |
Let's explore common operations on structured data.
|
| 47 |
+
|
| 48 |
+
**Try it!** Try modifying the `users_data` above and see how the results
|
| 49 |
+
change!
|
| 50 |
"""
|
| 51 |
)
|
| 52 |
return
|
|
|
|
| 55 |
@app.cell
|
| 56 |
def _(users_data):
|
| 57 |
# Finding users with specific skills
|
| 58 |
+
python_users = [
|
| 59 |
+
user["name"] for user in users_data if "Python" in user["skills"]
|
| 60 |
+
]
|
| 61 |
print("Python developers:", python_users)
|
| 62 |
return (python_users,)
|
| 63 |
|
| 64 |
|
| 65 |
@app.cell(hide_code=True)
|
| 66 |
def _(mo):
|
| 67 |
+
mo.md(
|
| 68 |
+
"""
|
| 69 |
+
## Nested data structures
|
| 70 |
|
| 71 |
Python collections can be nested in various ways to represent complex data:
|
| 72 |
+
"""
|
| 73 |
+
)
|
| 74 |
return
|
| 75 |
|
| 76 |
|
|
|
|
| 109 |
|
| 110 |
@app.cell(hide_code=True)
|
| 111 |
def _(mo):
|
| 112 |
+
mo.md(
|
| 113 |
+
"""
|
| 114 |
+
### Example: data transformation
|
| 115 |
|
| 116 |
Let's explore how to transform and reshape collection data:
|
| 117 |
+
"""
|
| 118 |
+
)
|
| 119 |
return
|
| 120 |
|
| 121 |
|
|
|
|
| 149 |
|
| 150 |
@app.cell(hide_code=True)
|
| 151 |
def _(mo):
|
| 152 |
+
mo.md(
|
| 153 |
+
"""
|
| 154 |
+
## More collection utilities
|
| 155 |
|
| 156 |
+
Python's `collections` module provides specialized container datatypes:
|
| 157 |
|
| 158 |
```python
|
| 159 |
from collections import defaultdict, Counter, deque
|
|
|
|
| 171 |
history = deque(maxlen=10) # Only keeps last 10 items
|
| 172 |
history.append(item)
|
| 173 |
```
|
| 174 |
+
"""
|
| 175 |
+
)
|
| 176 |
return
|
| 177 |
|
| 178 |
|
|
|
|
| 194 |
|
| 195 |
@app.cell(hide_code=True)
|
| 196 |
def _(mo):
|
| 197 |
+
mo.md(
|
| 198 |
+
"""
|
| 199 |
+
## Next steps
|
|
|
|
| 200 |
|
| 201 |
+
For a reference on the `collections` module, see [the official Python
|
| 202 |
+
docs](https://docs.python.org/3/library/collections.html).
|
| 203 |
+
"""
|
| 204 |
+
)
|
| 205 |
+
return
|
| 206 |
|
|
|
|
|
|
|
| 207 |
|
| 208 |
+
@app.cell
|
| 209 |
+
def _():
|
| 210 |
+
import marimo as mo
|
| 211 |
+
return (mo,)
|
| 212 |
|
| 213 |
|
| 214 |
if __name__ == "__main__":
|
Python/phase_4/function_design.py → python/008_functions.py
RENAMED
|
@@ -7,57 +7,69 @@
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
-
__generated_with = "0.10.
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
| 14 |
-
@app.cell
|
| 15 |
-
def _():
|
| 16 |
-
import marimo as mo
|
| 17 |
-
return (mo,)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
@app.cell(hide_code=True)
|
| 21 |
def _(mo):
|
| 22 |
mo.md(
|
| 23 |
"""
|
| 24 |
-
# 🧩
|
| 25 |
|
| 26 |
-
|
| 27 |
|
| 28 |
-
|
| 29 |
-
Functions help you:
|
| 30 |
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
- Create reusable code blocks
|
| 34 |
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
| 43 |
"""
|
| 44 |
)
|
| 45 |
return
|
| 46 |
|
| 47 |
|
| 48 |
@app.cell
|
| 49 |
-
def _():
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
|
| 54 |
-
name = "Python Learner"
|
| 55 |
-
return greet, name
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
| 61 |
return
|
| 62 |
|
| 63 |
|
|
@@ -65,7 +77,7 @@ def _(greet, name):
|
|
| 65 |
def _(mo):
|
| 66 |
mo.md(
|
| 67 |
"""
|
| 68 |
-
## Default
|
| 69 |
Make your functions more flexible by providing default values.
|
| 70 |
"""
|
| 71 |
)
|
|
@@ -74,21 +86,30 @@ def _(mo):
|
|
| 74 |
|
| 75 |
@app.cell
|
| 76 |
def _():
|
| 77 |
-
# Function with default parameter
|
| 78 |
def create_profile(name, age=18):
|
| 79 |
return f"{name} is {age} years old"
|
|
|
|
|
|
|
| 80 |
|
|
|
|
|
|
|
| 81 |
# Example usage
|
| 82 |
example_name = "Alex"
|
| 83 |
example_profile = create_profile(example_name)
|
| 84 |
example_profile
|
| 85 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
|
| 88 |
@app.cell
|
| 89 |
def _():
|
| 90 |
-
# Show closure over values
|
| 91 |
base_multiplier = 2
|
|
|
|
| 92 |
def multiplier(x):
|
| 93 |
"""
|
| 94 |
Create a function that multiplies input by a base value.
|
|
@@ -97,49 +118,12 @@ def _():
|
|
| 97 |
values from their surrounding scope.
|
| 98 |
"""
|
| 99 |
return x * base_multiplier
|
| 100 |
-
|
| 101 |
-
# Example of using the closure
|
| 102 |
-
sample_numbers = [1, 2, 3, 4, 5]
|
| 103 |
-
multiplied_numbers = [multiplier(num) for num in sample_numbers]
|
| 104 |
-
print(multiplied_numbers)
|
| 105 |
-
return base_multiplier, multiplied_numbers, multiplier, sample_numbers
|
| 106 |
|
| 107 |
|
| 108 |
@app.cell
|
| 109 |
-
def _():
|
| 110 |
-
|
| 111 |
-
"""
|
| 112 |
-
Perform multiple calculations on two numbers.
|
| 113 |
-
|
| 114 |
-
Args:
|
| 115 |
-
a (int): First number
|
| 116 |
-
b (int): Second number
|
| 117 |
-
|
| 118 |
-
Returns:
|
| 119 |
-
dict: Results of various calculations
|
| 120 |
-
"""
|
| 121 |
-
return {
|
| 122 |
-
"sum": a + b,
|
| 123 |
-
"product": a * b,
|
| 124 |
-
"difference": a - b,
|
| 125 |
-
"max": max(a, b)
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
-
# Example usage with concrete values
|
| 129 |
-
first_number = 10
|
| 130 |
-
second_number = 5
|
| 131 |
-
result = calculate(first_number, second_number)
|
| 132 |
-
return calculate, first_number, result, second_number
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
@app.cell(hide_code=True)
|
| 136 |
-
def _(mo, result):
|
| 137 |
-
mo.md(f"""
|
| 138 |
-
## Function Results
|
| 139 |
-
|
| 140 |
-
Calculation Results:
|
| 141 |
-
{result}
|
| 142 |
-
""")
|
| 143 |
return
|
| 144 |
|
| 145 |
|
|
@@ -147,16 +131,10 @@ def _(mo, result):
|
|
| 147 |
def _(mo):
|
| 148 |
mo.md(
|
| 149 |
"""
|
| 150 |
-
##
|
| 151 |
-
Python allows returning multiple values easily:
|
| 152 |
-
|
| 153 |
-
```python
|
| 154 |
-
def multiple_returns():
|
| 155 |
-
return value1, value2, value3
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
```
|
| 160 |
"""
|
| 161 |
)
|
| 162 |
return
|
|
@@ -182,47 +160,26 @@ def _():
|
|
| 182 |
return "Mild", "Comfortable clothing", "Low"
|
| 183 |
else:
|
| 184 |
return "Hot", "Stay hydrated", "High"
|
|
|
|
| 185 |
|
| 186 |
-
# Example temperature analysis
|
| 187 |
-
temperature = 25
|
| 188 |
-
status, recommendation, warning_level = weather_analysis(temperature)
|
| 189 |
-
return (
|
| 190 |
-
recommendation,
|
| 191 |
-
status,
|
| 192 |
-
temperature,
|
| 193 |
-
warning_level,
|
| 194 |
-
weather_analysis,
|
| 195 |
-
)
|
| 196 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
-
@app.cell(hide_code=True)
|
| 199 |
-
def _(mo, recommendation, status, warning_level):
|
| 200 |
-
mo.md(f"""
|
| 201 |
-
## Function Results
|
| 202 |
-
|
| 203 |
-
Calculation Results:
|
| 204 |
-
{status}, {recommendation}, {warning_level}
|
| 205 |
-
""")
|
| 206 |
-
return
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
@app.cell(hide_code=True)
|
| 210 |
-
def _(mo):
|
| 211 |
-
callout_text = mo.md("""
|
| 212 |
-
## Your Function Design Journey!
|
| 213 |
-
|
| 214 |
-
Next Steps:
|
| 215 |
-
|
| 216 |
-
- Practice creating functions
|
| 217 |
-
|
| 218 |
-
- Experiment with default parameters
|
| 219 |
|
| 220 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
-
""")
|
| 223 |
|
| 224 |
-
|
| 225 |
-
|
|
|
|
|
|
|
| 226 |
|
| 227 |
|
| 228 |
if __name__ == "__main__":
|
|
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
+
__generated_with = "0.10.19"
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
@app.cell(hide_code=True)
|
| 15 |
def _(mo):
|
| 16 |
mo.md(
|
| 17 |
"""
|
| 18 |
+
# 🧩 Functions
|
| 19 |
|
| 20 |
+
This tutorial is about an important topic: **functions.**
|
| 21 |
|
| 22 |
+
A function is a reusable block of code, similar in spirit to a mathematical function. Each function has a **name**, and accepts some number of **arguments**. These arguments are used in the function "body" (its block of code), and each function can **return** values.
|
|
|
|
| 23 |
|
| 24 |
+
**Example.** Below is an example function.
|
| 25 |
+
"""
|
| 26 |
+
)
|
| 27 |
+
return
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@app.cell
|
| 31 |
+
def _():
|
| 32 |
+
def greet(your_name):
|
| 33 |
+
return f"Hello, {your_name}!"
|
| 34 |
+
return (greet,)
|
| 35 |
|
|
|
|
| 36 |
|
| 37 |
+
@app.cell(hide_code=True)
|
| 38 |
+
def _(mo):
|
| 39 |
+
mo.md(r"""The keyword `def` starts the function definition. The function's **name** is `greet`. It accepts one **argument** called `your_name`. It then creates a string and **returns** it.""")
|
| 40 |
+
return
|
| 41 |
|
| 42 |
+
|
| 43 |
+
@app.cell(hide_code=True)
|
| 44 |
+
def _(mo):
|
| 45 |
+
mo.md(
|
| 46 |
+
"""
|
| 47 |
+
In the next cell, we **call** the function with a value and assign its return value to a variable.
|
| 48 |
+
|
| 49 |
+
**Try it!** Try changing the input to the function.
|
| 50 |
"""
|
| 51 |
)
|
| 52 |
return
|
| 53 |
|
| 54 |
|
| 55 |
@app.cell
|
| 56 |
+
def _(greet):
|
| 57 |
+
greeting = greet(your_name="<your name here>")
|
| 58 |
+
greeting
|
| 59 |
+
return (greeting,)
|
| 60 |
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
@app.cell(hide_code=True)
|
| 63 |
+
def _(mo):
|
| 64 |
+
mo.md(
|
| 65 |
+
"""
|
| 66 |
+
**Why use functions?** Functions help you:
|
| 67 |
|
| 68 |
+
- Break down complex problems
|
| 69 |
+
- Create reusable code blocks
|
| 70 |
+
- Improve code readability
|
| 71 |
+
"""
|
| 72 |
+
)
|
| 73 |
return
|
| 74 |
|
| 75 |
|
|
|
|
| 77 |
def _(mo):
|
| 78 |
mo.md(
|
| 79 |
"""
|
| 80 |
+
## Default parameters
|
| 81 |
Make your functions more flexible by providing default values.
|
| 82 |
"""
|
| 83 |
)
|
|
|
|
| 86 |
|
| 87 |
@app.cell
|
| 88 |
def _():
|
|
|
|
| 89 |
def create_profile(name, age=18):
|
| 90 |
return f"{name} is {age} years old"
|
| 91 |
+
return (create_profile,)
|
| 92 |
+
|
| 93 |
|
| 94 |
+
@app.cell
|
| 95 |
+
def _(create_profile):
|
| 96 |
# Example usage
|
| 97 |
example_name = "Alex"
|
| 98 |
example_profile = create_profile(example_name)
|
| 99 |
example_profile
|
| 100 |
+
return example_name, example_profile
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@app.cell(hide_code=True)
|
| 104 |
+
def _(mo):
|
| 105 |
+
mo.md("""You can also create functions that reference variables outside the function body. This is called 'closing over' variables""")
|
| 106 |
+
return
|
| 107 |
|
| 108 |
|
| 109 |
@app.cell
|
| 110 |
def _():
|
|
|
|
| 111 |
base_multiplier = 2
|
| 112 |
+
|
| 113 |
def multiplier(x):
|
| 114 |
"""
|
| 115 |
Create a function that multiplies input by a base value.
|
|
|
|
| 118 |
values from their surrounding scope.
|
| 119 |
"""
|
| 120 |
return x * base_multiplier
|
| 121 |
+
return base_multiplier, multiplier
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
|
| 124 |
@app.cell
|
| 125 |
+
def _(multiplier):
|
| 126 |
+
print([multiplier(num) for num in [1, 2, 3]])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
return
|
| 128 |
|
| 129 |
|
|
|
|
| 131 |
def _(mo):
|
| 132 |
mo.md(
|
| 133 |
"""
|
| 134 |
+
## Returning multiple values
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
Functions can return multiple values: just separate the values to return by
|
| 137 |
+
commas. Check out the next cell for an example.
|
|
|
|
| 138 |
"""
|
| 139 |
)
|
| 140 |
return
|
|
|
|
| 160 |
return "Mild", "Comfortable clothing", "Low"
|
| 161 |
else:
|
| 162 |
return "Hot", "Stay hydrated", "High"
|
| 163 |
+
return (weather_analysis,)
|
| 164 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
+
@app.cell
|
| 167 |
+
def _():
|
| 168 |
+
temperature = 25
|
| 169 |
+
return (temperature,)
|
| 170 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
+
@app.cell
|
| 173 |
+
def _(temperature, weather_analysis):
|
| 174 |
+
status, recommendation, warning_level = weather_analysis(temperature)
|
| 175 |
+
status, recommendation, warning_level
|
| 176 |
+
return recommendation, status, warning_level
|
| 177 |
|
|
|
|
| 178 |
|
| 179 |
+
@app.cell
|
| 180 |
+
def _():
|
| 181 |
+
import marimo as mo
|
| 182 |
+
return (mo,)
|
| 183 |
|
| 184 |
|
| 185 |
if __name__ == "__main__":
|
Python/phase_4/modular_programming.py → python/009_modules.py
RENAMED
|
@@ -7,29 +7,21 @@
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
-
__generated_with = "0.10.
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
| 14 |
-
@app.cell
|
| 15 |
-
def _():
|
| 16 |
-
import marimo as mo
|
| 17 |
-
return (mo,)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
@app.cell(hide_code=True)
|
| 21 |
def _(mo):
|
| 22 |
mo.md(
|
| 23 |
"""
|
| 24 |
-
# 🧩
|
| 25 |
|
| 26 |
-
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
- Improve code readability
|
| 31 |
-
- Enhance code reusability
|
| 32 |
-
- Easier debugging and maintenance
|
| 33 |
"""
|
| 34 |
)
|
| 35 |
return
|
|
@@ -39,8 +31,9 @@ def _(mo):
|
|
| 39 |
def _(mo):
|
| 40 |
mo.md(
|
| 41 |
"""
|
| 42 |
-
##
|
| 43 |
-
|
|
|
|
| 44 |
|
| 45 |
```python
|
| 46 |
# String manipulation
|
|
@@ -56,15 +49,20 @@ def _(mo):
|
|
| 56 |
import math
|
| 57 |
```
|
| 58 |
|
| 59 |
-
|
| 60 |
"""
|
| 61 |
)
|
| 62 |
return
|
| 63 |
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
@app.cell
|
| 66 |
def _():
|
| 67 |
-
# importing and using standard library modules
|
| 68 |
import string
|
| 69 |
import os
|
| 70 |
import datetime
|
|
@@ -108,8 +106,9 @@ def _():
|
|
| 108 |
def _(mo):
|
| 109 |
mo.md(
|
| 110 |
"""
|
| 111 |
-
## Import
|
| 112 |
-
|
|
|
|
| 113 |
|
| 114 |
```python
|
| 115 |
# Import entire module
|
|
@@ -160,8 +159,16 @@ def _():
|
|
| 160 |
def _(mo):
|
| 161 |
mo.md(
|
| 162 |
"""
|
| 163 |
-
##
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
"""
|
| 166 |
)
|
| 167 |
return
|
|
@@ -169,64 +176,8 @@ def _(mo):
|
|
| 169 |
|
| 170 |
@app.cell
|
| 171 |
def _():
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
Demonstrate different types of reusable functions
|
| 175 |
-
"""
|
| 176 |
-
|
| 177 |
-
def process_text(text):
|
| 178 |
-
'''Reusable text processing function'''
|
| 179 |
-
return text.strip().lower()
|
| 180 |
-
|
| 181 |
-
def normalize_number(value, min_val=0, max_val=100):
|
| 182 |
-
'''Normalize a number to a specific range'''
|
| 183 |
-
return max(min_val, min(max_val, value))
|
| 184 |
-
|
| 185 |
-
def validate_input(value, type_check=str, min_length=1):
|
| 186 |
-
'''Validate input based on type and minimum length'''
|
| 187 |
-
if not isinstance(value, type_check):
|
| 188 |
-
return False
|
| 189 |
-
return len(str(value)) >= min_length
|
| 190 |
-
|
| 191 |
-
# usage
|
| 192 |
-
return {
|
| 193 |
-
"Text Processing": {
|
| 194 |
-
"Example 1": process_text(" John Doe "),
|
| 195 |
-
"Example 2": process_text(" Example@Email.com ")
|
| 196 |
-
},
|
| 197 |
-
"Number Normalization": {
|
| 198 |
-
"Oversized Input": normalize_number(150),
|
| 199 |
-
"Negative Input": normalize_number(-10, min_val=-20, max_val=50)
|
| 200 |
-
},
|
| 201 |
-
"Input Validation": {
|
| 202 |
-
"Username Validation": validate_input("john"),
|
| 203 |
-
"Age Validation": validate_input(25, type_check=int)
|
| 204 |
-
}
|
| 205 |
-
}
|
| 206 |
-
|
| 207 |
-
# Run the reusable functions demonstration
|
| 208 |
-
reusable_function_examples = generate_reusable_functions()
|
| 209 |
-
reusable_function_examples
|
| 210 |
-
return generate_reusable_functions, reusable_function_examples
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
@app.cell(hide_code=True)
|
| 214 |
-
def _(mo):
|
| 215 |
-
callout_text = mo.md("""
|
| 216 |
-
## Your Modular Programming Journey!
|
| 217 |
-
|
| 218 |
-
Next Steps:
|
| 219 |
-
|
| 220 |
-
- Explore Python's standard library
|
| 221 |
-
|
| 222 |
-
- Practice different import strategies
|
| 223 |
-
|
| 224 |
-
- Design reusable functions
|
| 225 |
-
|
| 226 |
-
""")
|
| 227 |
-
|
| 228 |
-
mo.callout(callout_text, kind="success")
|
| 229 |
-
return (callout_text,)
|
| 230 |
|
| 231 |
|
| 232 |
if __name__ == "__main__":
|
|
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
+
__generated_with = "0.10.19"
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
@app.cell(hide_code=True)
|
| 15 |
def _(mo):
|
| 16 |
mo.md(
|
| 17 |
"""
|
| 18 |
+
# 🧩 Using modules
|
| 19 |
|
| 20 |
+
A `module` in Python is a Python file that defines functions and variables. Modules can be `imported` into other Python files, letting you reuse their
|
| 21 |
+
functions and variables.
|
| 22 |
|
| 23 |
+
We have already seen some modules in previous tutorials, including the `math`
|
| 24 |
+
module. Python comes with many other modules built-in.
|
|
|
|
|
|
|
|
|
|
| 25 |
"""
|
| 26 |
)
|
| 27 |
return
|
|
|
|
| 31 |
def _(mo):
|
| 32 |
mo.md(
|
| 33 |
"""
|
| 34 |
+
## The Python standard library
|
| 35 |
+
|
| 36 |
+
Python's "standard library" provides many modules, for many kinds of tasks.
|
| 37 |
|
| 38 |
```python
|
| 39 |
# String manipulation
|
|
|
|
| 49 |
import math
|
| 50 |
```
|
| 51 |
|
| 52 |
+
See the [Python standard library documentation](https://docs.python.org/3/library/) for a full reference
|
| 53 |
"""
|
| 54 |
)
|
| 55 |
return
|
| 56 |
|
| 57 |
|
| 58 |
+
@app.cell(hide_code=True)
|
| 59 |
+
def _(mo):
|
| 60 |
+
mo.md("""### Example""")
|
| 61 |
+
return
|
| 62 |
+
|
| 63 |
+
|
| 64 |
@app.cell
|
| 65 |
def _():
|
|
|
|
| 66 |
import string
|
| 67 |
import os
|
| 68 |
import datetime
|
|
|
|
| 106 |
def _(mo):
|
| 107 |
mo.md(
|
| 108 |
"""
|
| 109 |
+
## Import syntax
|
| 110 |
+
|
| 111 |
+
You can import entire modules, and access their functions and variables using dot notation (`math.sqrt`). Or you can import specific members:
|
| 112 |
|
| 113 |
```python
|
| 114 |
# Import entire module
|
|
|
|
| 159 |
def _(mo):
|
| 160 |
mo.md(
|
| 161 |
"""
|
| 162 |
+
## Third-party packages
|
| 163 |
+
|
| 164 |
+
In addition to Python's standard library, there are hundreds of thousands of
|
| 165 |
+
modules available for free on the Python Package index.
|
| 166 |
+
|
| 167 |
+
These are distributed as Python "packages", and include packages for
|
| 168 |
+
manipulating arrays of numbers, creating web applications, and more. `marimo`
|
| 169 |
+
itself is a third-party package!
|
| 170 |
+
|
| 171 |
+
For installing packages on your machine, we recommend using the [`uv` package manager](https://docs.astral.sh/uv/).
|
| 172 |
"""
|
| 173 |
)
|
| 174 |
return
|
|
|
|
| 176 |
|
| 177 |
@app.cell
|
| 178 |
def _():
|
| 179 |
+
import marimo as mo
|
| 180 |
+
return (mo,)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
|
| 183 |
if __name__ == "__main__":
|
Python/phase_5/error_management.py → python/010_exceptions.py
RENAMED
|
@@ -7,44 +7,78 @@
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
-
__generated_with = "0.10.
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
@app.cell
|
| 15 |
def _():
|
| 16 |
-
|
| 17 |
-
return
|
| 18 |
|
| 19 |
|
| 20 |
@app.cell(hide_code=True)
|
| 21 |
def _(mo):
|
| 22 |
mo.md(
|
| 23 |
"""
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
Welcome to the world of Python error handling - where bugs become learning opportunities!
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
```python
|
| 33 |
-
# Without error handling
|
| 34 |
-
result = 10 / 0 # 💥 Boom! Unhandled ZeroDivisionError
|
| 35 |
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
try:
|
| 38 |
-
|
| 39 |
-
except
|
| 40 |
-
|
| 41 |
```
|
| 42 |
"""
|
| 43 |
)
|
| 44 |
return
|
| 45 |
|
| 46 |
|
| 47 |
-
@app.cell
|
| 48 |
def _(error_types):
|
| 49 |
error_types
|
| 50 |
return
|
|
@@ -54,6 +88,7 @@ def _(error_types):
|
|
| 54 |
def _(mo):
|
| 55 |
# Choose error type
|
| 56 |
error_types = mo.ui.dropdown(
|
|
|
|
| 57 |
options=[
|
| 58 |
"ZeroDivisionError",
|
| 59 |
"TypeError",
|
|
@@ -61,7 +96,7 @@ def _(mo):
|
|
| 61 |
"IndexError",
|
| 62 |
"KeyError"
|
| 63 |
],
|
| 64 |
-
label="
|
| 65 |
)
|
| 66 |
return (error_types,)
|
| 67 |
|
|
@@ -122,58 +157,12 @@ def _(error_types, mo):
|
|
| 122 |
return (error_explanations,)
|
| 123 |
|
| 124 |
|
| 125 |
-
@app.cell
|
| 126 |
-
def _(division_input, divisor_input, mo):
|
| 127 |
-
mo.hstack([division_input, divisor_input])
|
| 128 |
-
return
|
| 129 |
-
|
| 130 |
-
|
| 131 |
@app.cell(hide_code=True)
|
| 132 |
def _(mo):
|
| 133 |
-
# Try-Except work help
|
| 134 |
-
division_input = mo.ui.number(
|
| 135 |
-
value=10,
|
| 136 |
-
label="Number to Divide",
|
| 137 |
-
start=-100,
|
| 138 |
-
stop=100
|
| 139 |
-
)
|
| 140 |
-
divisor_input = mo.ui.number(
|
| 141 |
-
value=0,
|
| 142 |
-
label="Divisor",
|
| 143 |
-
start=-100,
|
| 144 |
-
stop=100
|
| 145 |
-
)
|
| 146 |
-
return division_input, divisor_input
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
@app.cell
|
| 150 |
-
def _(division_input, divisor_input, mo):
|
| 151 |
-
# Safe division function with appropriate error handling
|
| 152 |
-
def safe_divide(numerator, denominator):
|
| 153 |
-
try:
|
| 154 |
-
_result = numerator / denominator
|
| 155 |
-
return f"Result: {_result}"
|
| 156 |
-
except ZeroDivisionError:
|
| 157 |
-
return "🚫 Cannot divide by zero!"
|
| 158 |
-
except Exception as e:
|
| 159 |
-
return f"Unexpected error: {e}"
|
| 160 |
-
|
| 161 |
-
# Display result with explanation
|
| 162 |
-
_result = safe_divide(division_input.value, divisor_input.value)
|
| 163 |
-
|
| 164 |
-
mo.hstack([
|
| 165 |
-
mo.md(f"**Division**: {division_input.value} ÷ {divisor_input.value}"),
|
| 166 |
-
mo.md(f"**Result**: {_result}")
|
| 167 |
-
])
|
| 168 |
-
return (safe_divide,)
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
@app.cell
|
| 172 |
-
def _(mo):
|
| 173 |
-
# Multiple Exception Handling
|
| 174 |
mo.md(
|
| 175 |
"""
|
| 176 |
-
##
|
|
|
|
| 177 |
Catch and handle different types of errors specifically:
|
| 178 |
|
| 179 |
```python
|
|
@@ -188,64 +177,28 @@ def _(mo):
|
|
| 188 |
return "No division by zero!"
|
| 189 |
except ValueError:
|
| 190 |
return "Conversion error!"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
```
|
| 192 |
"""
|
| 193 |
)
|
| 194 |
return
|
| 195 |
|
| 196 |
|
| 197 |
-
@app.cell
|
| 198 |
-
def _(error_chain_input):
|
| 199 |
-
error_chain_input
|
| 200 |
-
return
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
@app.cell
|
| 204 |
-
def _(mo):
|
| 205 |
-
# Try it out
|
| 206 |
-
error_chain_input = mo.ui.text(
|
| 207 |
-
label="Try to break the code",
|
| 208 |
-
placeholder="Enter something tricky..."
|
| 209 |
-
)
|
| 210 |
-
return (error_chain_input,)
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
@app.cell
|
| 214 |
-
def _(error_chain_input, mo):
|
| 215 |
-
# Error chain demonstration
|
| 216 |
-
def tricky_function(input_str):
|
| 217 |
-
try:
|
| 218 |
-
# Simulating a error scenario
|
| 219 |
-
number = int(input_str)
|
| 220 |
-
result = 100 / number
|
| 221 |
-
return f"Success! Result: {result}"
|
| 222 |
-
except ValueError:
|
| 223 |
-
return "❌ Could not convert to number"
|
| 224 |
-
except ZeroDivisionError:
|
| 225 |
-
return "❌ Cannot divide by zero"
|
| 226 |
-
except Exception as e:
|
| 227 |
-
return f"🤯 Unexpected error: {type(e).__name__}"
|
| 228 |
-
|
| 229 |
-
result = tricky_function(error_chain_input.value)
|
| 230 |
-
|
| 231 |
-
mo.hstack([
|
| 232 |
-
mo.md(f"**Input**: {error_chain_input.value}"),
|
| 233 |
-
mo.md(f"**Result**: {result}")
|
| 234 |
-
])
|
| 235 |
-
return result, tricky_function
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
@app.cell
|
| 239 |
def _(finally_input):
|
| 240 |
finally_input
|
| 241 |
return
|
| 242 |
|
| 243 |
|
| 244 |
-
@app.cell
|
| 245 |
def _(mo):
|
| 246 |
# Finally Block Demonstration
|
| 247 |
finally_input = mo.ui.switch(
|
| 248 |
-
label="
|
| 249 |
value=True
|
| 250 |
)
|
| 251 |
return (finally_input,)
|
|
@@ -256,7 +209,7 @@ def _(finally_input, mo):
|
|
| 256 |
def simulate_resource_management():
|
| 257 |
try:
|
| 258 |
# Simulating a resource-intensive operation
|
| 259 |
-
if finally_input.value:
|
| 260 |
return "🟢 Resource processing successful"
|
| 261 |
else:
|
| 262 |
raise Exception("Simulated failure")
|
|
@@ -265,12 +218,13 @@ def _(finally_input, mo):
|
|
| 265 |
finally:
|
| 266 |
return "📦 Resource cleanup completed"
|
| 267 |
|
|
|
|
| 268 |
_result = simulate_resource_management()
|
| 269 |
|
| 270 |
mo.md(f"""
|
| 271 |
-
###
|
| 272 |
|
| 273 |
-
**Scenario**: {
|
| 274 |
|
| 275 |
**Result**: {_result}
|
| 276 |
|
|
@@ -279,22 +233,10 @@ def _(finally_input, mo):
|
|
| 279 |
return (simulate_resource_management,)
|
| 280 |
|
| 281 |
|
| 282 |
-
@app.cell
|
| 283 |
-
def _(
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
Next Steps:
|
| 288 |
-
|
| 289 |
-
- Practice creating custom exceptions
|
| 290 |
-
- Explore context managers
|
| 291 |
-
- Build robust error-handling strategies
|
| 292 |
-
|
| 293 |
-
You're becoming a Python error-handling ninja! 🥷🐍
|
| 294 |
-
""")
|
| 295 |
-
|
| 296 |
-
mo.callout(callout_text, kind="success")
|
| 297 |
-
return (callout_text,)
|
| 298 |
|
| 299 |
|
| 300 |
if __name__ == "__main__":
|
|
|
|
| 7 |
|
| 8 |
import marimo
|
| 9 |
|
| 10 |
+
__generated_with = "0.10.19"
|
| 11 |
app = marimo.App()
|
| 12 |
|
| 13 |
|
| 14 |
+
@app.cell(hide_code=True)
|
| 15 |
+
def _(mo):
|
| 16 |
+
mo.md(
|
| 17 |
+
"""
|
| 18 |
+
# 🛡️ Handling errors
|
| 19 |
+
|
| 20 |
+
Sometimes things go wrong in programs. When that happens, Python raises `exceptions` to tell you what went amiss. For example, maybe you divided by 0:
|
| 21 |
+
"""
|
| 22 |
+
)
|
| 23 |
+
return
|
| 24 |
+
|
| 25 |
+
|
| 26 |
@app.cell
|
| 27 |
def _():
|
| 28 |
+
1 / 0
|
| 29 |
+
return
|
| 30 |
|
| 31 |
|
| 32 |
@app.cell(hide_code=True)
|
| 33 |
def _(mo):
|
| 34 |
mo.md(
|
| 35 |
"""
|
| 36 |
+
That's a lot of red! The outputs above are Python telling you that
|
| 37 |
+
something went wrong — in this case, we tried dividing a number by 0.
|
| 38 |
+
|
| 39 |
+
Python provides tools to catch and handle exceptions: the `try/except`
|
| 40 |
+
block. This is demonstrated in the next couple cells.
|
| 41 |
+
"""
|
| 42 |
+
)
|
| 43 |
+
return
|
| 44 |
|
|
|
|
| 45 |
|
| 46 |
+
@app.cell
|
| 47 |
+
def _():
|
| 48 |
+
# Try changing the value of divisor below, and see how the output changes.
|
| 49 |
+
divisor = 0
|
| 50 |
+
return (divisor,)
|
| 51 |
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
@app.cell
|
| 54 |
+
def _(divisor):
|
| 55 |
+
try:
|
| 56 |
+
print(1 / divisor)
|
| 57 |
+
except ZeroDivisionError as e:
|
| 58 |
+
print("Something went wrong!", e)
|
| 59 |
+
return
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@app.cell(hide_code=True)
|
| 63 |
+
def _(mo):
|
| 64 |
+
mo.md(
|
| 65 |
+
"""
|
| 66 |
+
Python has many types of Exceptions besides `ZeroDivisionError`. If you
|
| 67 |
+
don't know what kind of exception you're handling, catch the generic
|
| 68 |
+
`Exception` type:
|
| 69 |
+
|
| 70 |
+
```python
|
| 71 |
try:
|
| 72 |
+
...
|
| 73 |
+
except Exception:
|
| 74 |
+
...
|
| 75 |
```
|
| 76 |
"""
|
| 77 |
)
|
| 78 |
return
|
| 79 |
|
| 80 |
|
| 81 |
+
@app.cell(hide_code=True)
|
| 82 |
def _(error_types):
|
| 83 |
error_types
|
| 84 |
return
|
|
|
|
| 88 |
def _(mo):
|
| 89 |
# Choose error type
|
| 90 |
error_types = mo.ui.dropdown(
|
| 91 |
+
value="ZeroDivisionError",
|
| 92 |
options=[
|
| 93 |
"ZeroDivisionError",
|
| 94 |
"TypeError",
|
|
|
|
| 96 |
"IndexError",
|
| 97 |
"KeyError"
|
| 98 |
],
|
| 99 |
+
label="Learn about ..."
|
| 100 |
)
|
| 101 |
return (error_types,)
|
| 102 |
|
|
|
|
| 157 |
return (error_explanations,)
|
| 158 |
|
| 159 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
@app.cell(hide_code=True)
|
| 161 |
def _(mo):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
mo.md(
|
| 163 |
"""
|
| 164 |
+
## Handling multiple exception types
|
| 165 |
+
|
| 166 |
Catch and handle different types of errors specifically:
|
| 167 |
|
| 168 |
```python
|
|
|
|
| 177 |
return "No division by zero!"
|
| 178 |
except ValueError:
|
| 179 |
return "Conversion error!"
|
| 180 |
+
finally:
|
| 181 |
+
# The `finally` block always runs, regardless if there
|
| 182 |
+
# was an error or not
|
| 183 |
+
...
|
| 184 |
+
|
| 185 |
```
|
| 186 |
"""
|
| 187 |
)
|
| 188 |
return
|
| 189 |
|
| 190 |
|
| 191 |
+
@app.cell(hide_code=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
def _(finally_input):
|
| 193 |
finally_input
|
| 194 |
return
|
| 195 |
|
| 196 |
|
| 197 |
+
@app.cell(hide_code=True)
|
| 198 |
def _(mo):
|
| 199 |
# Finally Block Demonstration
|
| 200 |
finally_input = mo.ui.switch(
|
| 201 |
+
label="Throw an error?",
|
| 202 |
value=True
|
| 203 |
)
|
| 204 |
return (finally_input,)
|
|
|
|
| 209 |
def simulate_resource_management():
|
| 210 |
try:
|
| 211 |
# Simulating a resource-intensive operation
|
| 212 |
+
if not finally_input.value:
|
| 213 |
return "🟢 Resource processing successful"
|
| 214 |
else:
|
| 215 |
raise Exception("Simulated failure")
|
|
|
|
| 218 |
finally:
|
| 219 |
return "📦 Resource cleanup completed"
|
| 220 |
|
| 221 |
+
|
| 222 |
_result = simulate_resource_management()
|
| 223 |
|
| 224 |
mo.md(f"""
|
| 225 |
+
### Example: the finally clause
|
| 226 |
|
| 227 |
+
**Scenario**: {"Normal operation" if not finally_input.value else "An exception was raised"}
|
| 228 |
|
| 229 |
**Result**: {_result}
|
| 230 |
|
|
|
|
| 233 |
return (simulate_resource_management,)
|
| 234 |
|
| 235 |
|
| 236 |
+
@app.cell
|
| 237 |
+
def _():
|
| 238 |
+
import marimo as mo
|
| 239 |
+
return (mo,)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
|
| 242 |
if __name__ == "__main__":
|
{Python → python}/README.md
RENAMED
|
File without changes
|