pyodide: loading…

[concept]String & File Ops

Error Handling

# theory

try/except

Catch errors and handle them gracefully:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

common exception types

ExceptionWhen it occurs
ValueErrorWrong value (e.g., int("abc"))
KeyErrorDict key doesn't exist
IndexErrorList index out of range
FileNotFoundErrorFile doesn't exist
TypeErrorWrong type for operation
ZeroDivisionErrorDivision by zero

multiple exceptions

try:
    # risky code
    value = int(user_input)
    result = data[value]
except ValueError:
    print("Not a valid number")
except KeyError:
    print("Key not found")
except (IndexError, TypeError) as e:
    print(f"Error: {e}")

else and finally

try:
    file = open("data.txt")
except FileNotFoundError:
    print("File not found")
else:
    # Runs only if no exception
    content = file.read()
    file.close()
finally:
    # Always runs
    print("Done")

raising

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

# examples [3]

# example 01 · safe type conversion

Handle invalid input gracefully

1
2
3
4
5
6
7
8
9
10
🐍
Loading PythonSetting up pandas & numpy...
# example 02 · dictionary access with default

Handle missing keys gracefully

1
2
3
4
5
6
7
8
9
10
11
12
13
14
🐍
Loading PythonSetting up pandas & numpy...
# example 03 · processing with error handling

Continue processing even when some items fail

1
2
3
4
5
6
7
8
9
10
11
12
🐍
Loading PythonSetting up pandas & numpy...

# challenges [2]

# challenge 01/02todo
Write a function safe_get(lst, index) that returns the item at index, or 'Not found' if index is out of range.
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
🐍
Loading PythonSetting up pandas & numpy...
# challenge 02/02todo
Convert ['1', '2', 'x', '4'] to integers, skipping invalid values. Print the sum of valid numbers.
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
🐍
Loading PythonSetting up pandas & numpy...

# project

# project-challenge

thread: Sales Performance Dashboard · reward: 50 xp

# brief

Some sales records might have invalid data. Create a function that safely calculates revenue, handling cases where Quantity or UnitPrice might be invalid, and returns 0 for those records.

# task

Safe Revenue Calculator

# your code
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
🐍
Loading PythonSetting up pandas & numpy...