Lesson 08 of 55
9 mins readPython Function Guards (| condition = result)
In Plain English
Guards test values using a pipe (|) syntax similar to mathematical piecewise functions. The special identifier otherwise acts as a catch-all fallback.
Deep Dive: How It Works
Guard Syntax: pipe character (|) followed by a boolean condition, equals (=), and result expression.
otherwise: In Haskell prelude, otherwise is simply defined as True, serving as an idiomatic default case.
Readability: Guards provide cleaner syntax than deeply nested if-then-else expressions.
Core Rules to Remember

Piecewise Mathematical Syntax: Test sequential conditions cleanly: | x < 0 = "Negative" | x > 0 = "Positive".

otherwise Catch-All: Guarantees that a value is produced if prior conditions fail.
Live Interactive Example
Hit Run Code to see it liveGrade Classifier with Guards
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: Haskell checks each guard from top to bottom until the first True condition.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Check Number Sign with Guards
Define `numSign n | n > 0 = "Positive" | n < 0 = "Negative" | otherwise = "Zero"`.
Print `"Sign of -5: "` followed by `numSign (-5)`.
1
2
3
4
5
6
7
8
9
10
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.