Editor

Strategy Pattern with Functions

Advanced · Write the code · from Python Design Patterns: Factory, Strategy, Observer, and More

From the lesson: Python Design Patterns: Factory, Strategy, Observer, and More

Design patterns are proven recipes for solving common software problems. Think of them like architectural blueprints -- you wouldn't redesign plumbing from scratch for every house. Patterns give your code a shared vocabulary so other developers instantly understand your intent.

Read the lesson

Create a function apply_discount(price, strategy) that takes a price and a discount strategy function, then returns the discounted price.

Define two strategy functions:

  • half_off(price) -- returns price * 0.5
  • ten_percent(price) -- returns price * 0.9
  • Print the result of applying half_off to a price of 100, then print the result of applying ten_percent to 100.

    # Define discount strategies and apply_discount

    More Design Patterns exercises

    All Python exercises · 50 practice problems · Advanced Python quiz