Spaces:
Running
Running
File size: 7,339 Bytes
e9ef2cd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "marimo",
# ]
# ///
import marimo
__generated_with = "0.10.16"
app = marimo.App()
@app.cell
def _():
import marimo as mo
return (mo,)
@app.cell(hide_code=True)
def _(mo):
mo.md(
"""
# π‘οΈ Error Management in Python
Welcome to the world of Python error handling - where bugs become learning opportunities!
## Why Error Handling Matters
Imagine your code as a superhero navigating through the treacherous landscape of potential problems.
Error handling is like your hero's shield, protecting your program from unexpected challenges.
```python
# Without error handling
result = 10 / 0 # π₯ Boom! Unhandled ZeroDivisionError
# With error handling
try:
result = 10 / 0
except ZeroDivisionError:
result = "Oops! Can't divide by zero π"
```
"""
)
return
@app.cell
def _(error_types):
error_types
return
@app.cell(hide_code=True)
def _(mo):
# Choose error type
error_types = mo.ui.dropdown(
options=[
"ZeroDivisionError",
"TypeError",
"ValueError",
"IndexError",
"KeyError"
],
label="Select an Error Type to Explore"
)
return (error_types,)
@app.cell(hide_code=True)
def _(error_types, mo):
# Error explanation
error_explanations = {
"ZeroDivisionError": """
### π« ZeroDivisionError
- Occurs when you try to divide by zero
- Mathematical impossibility
- Example:
```python
x = 10 / 0 # Triggers ZeroDivisionError
```
""",
"TypeError": """
### π TypeError
- Happens when an operation is applied to an inappropriate type
- Mixing incompatible types
- Example:
```python
"2" + 3 # Can't add string and integer
```
""",
"ValueError": """
### π ValueError
- Raised when a function receives an argument of correct type
but inappropriate value
- Example:
```python
int("hello") # Can't convert non-numeric string to int
```
""",
"IndexError": """
### π IndexError
- Occurs when trying to access a list index that doesn't exist
- Going beyond list boundaries
- Example:
```python
my_list = [1, 2, 3]
print(my_list[5]) # Only has indices 0, 1, 2
```
""",
"KeyError": """
### ποΈ KeyError
- Raised when trying to access a dictionary key that doesn't exist
- Example:
```python
my_dict = {"a": 1, "b": 2}
print(my_dict["c"]) # "c" key doesn't exist
```
"""
}
mo.md(error_explanations.get(error_types.value, "Select an error type"))
return (error_explanations,)
@app.cell
def _(division_input, divisor_input, mo):
mo.hstack([division_input, divisor_input])
return
@app.cell(hide_code=True)
def _(mo):
# Try-Except work help
division_input = mo.ui.number(
value=10,
label="Number to Divide",
start=-100,
stop=100
)
divisor_input = mo.ui.number(
value=0,
label="Divisor",
start=-100,
stop=100
)
return division_input, divisor_input
@app.cell
def _(division_input, divisor_input, mo):
# Safe division function with appropriate error handling
def safe_divide(numerator, denominator):
try:
_result = numerator / denominator
return f"Result: {_result}"
except ZeroDivisionError:
return "π« Cannot divide by zero!"
except Exception as e:
return f"Unexpected error: {e}"
# Display result with explanation
_result = safe_divide(division_input.value, divisor_input.value)
mo.hstack([
mo.md(f"**Division**: {division_input.value} Γ· {divisor_input.value}"),
mo.md(f"**Result**: {_result}")
])
return (safe_divide,)
@app.cell
def _(mo):
# Multiple Exception Handling
mo.md(
"""
## Multiple Exception Handling
Catch and handle different types of errors specifically:
```python
def complex_function(x, y):
try:
# Potential errors: TypeError, ZeroDivisionError
result = x / y
return int(result)
except TypeError:
return "Type mismatch!"
except ZeroDivisionError:
return "No division by zero!"
except ValueError:
return "Conversion error!"
```
"""
)
return
@app.cell
def _(error_chain_input):
error_chain_input
return
@app.cell
def _(mo):
# Try it out
error_chain_input = mo.ui.text(
label="Try to break the code",
placeholder="Enter something tricky..."
)
return (error_chain_input,)
@app.cell
def _(error_chain_input, mo):
# Error chain demonstration
def tricky_function(input_str):
try:
# Simulating a error scenario
number = int(input_str)
result = 100 / number
return f"Success! Result: {result}"
except ValueError:
return "β Could not convert to number"
except ZeroDivisionError:
return "β Cannot divide by zero"
except Exception as e:
return f"π€― Unexpected error: {type(e).__name__}"
result = tricky_function(error_chain_input.value)
mo.hstack([
mo.md(f"**Input**: {error_chain_input.value}"),
mo.md(f"**Result**: {result}")
])
return result, tricky_function
@app.cell
def _(finally_input):
finally_input
return
@app.cell
def _(mo):
# Finally Block Demonstration
finally_input = mo.ui.switch(
label="Simulate Resource Management",
value=True
)
return (finally_input,)
@app.cell
def _(finally_input, mo):
def simulate_resource_management():
try:
# Simulating a resource-intensive operation
if finally_input.value:
return "π’ Resource processing successful"
else:
raise Exception("Simulated failure")
except Exception as e:
return f"π΄ Error: {e}"
finally:
return "π¦ Resource cleanup completed"
_result = simulate_resource_management()
mo.md(f"""
### Resource Management Simulation
**Scenario**: {'Normal operation' if finally_input.value else 'Error scenario'}
**Result**: {_result}
Notice how the `finally` block always runs, ensuring cleanup!
""")
return (simulate_resource_management,)
@app.cell(hide_code=True)
def _(mo):
callout_text = mo.md("""
## Your Error Handling Journey Continues!
Next Steps:
- Practice creating custom exceptions
- Explore context managers
- Build robust error-handling strategies
You're becoming a Python error-handling ninja! π₯·π
""")
mo.callout(callout_text, kind="success")
return (callout_text,)
if __name__ == "__main__":
app.run()
|