Control Flow
Guard Clauses
The nested version is correct, but the useful work is buried inside both tests.
Source
def nested_discount(price, percent):
if price >= 0:
if 0 <= percent <= 100:
return round(price - price * percent / 100, 2)
return "invalid discount"
return "invalid price"
print(nested_discount(100, 15))Output
85.0The guard-clause version handles impossible inputs first, then lets the ordinary calculation sit at the top level of the function body.
Source
def guarded_discount(price, percent):
if price < 0:
return "invalid price"
if not 0 <= percent <= 100:
return "invalid discount"
return round(price - price * percent / 100, 2)
print(guarded_discount(-5, 10))
print(guarded_discount(100, 120))Output
invalid price
invalid discountNotes
- Guard clauses are a readability pattern, not a separate Python feature.
- They work best when the early cases are true boundaries.
- For exceptional failures, raise an exception instead of returning a sentinel string.
See also
- related: Conditionals
- next depth: Exceptions
- next depth: Functions
Run the complete example
Expected output
85.0
invalid price
invalid discount
Execution time appears here after you run the example.