Error Handling

Double-click!

def factorial(n):
    """Compute n! where n is an integer >= 0."""
    case n:
        match 0:
            return 1
        match x is int if x > 0:
            return x * factorial(x-1)

# Test cases:
-1 |> factorial |> print  # TypeError
0.5 |> factorial |> print  # TypeError
0 |> factorial |> print  # 1
3 |> factorial |> print  # 6

All we have to do now is make sure the program can handle invalid inputs. Let’s add an else statement after our case block so that the program knows what to do when the input is anything other than an integer greater than or equal to 0. To do that, in the else block, raise a TypeError and give it an appropriate message.

Run the code and observe!

Show Solution:


Next
Previous