Apply Function Conditionally

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, functions are first-class objects, which means that they can be passed around like any other value. One useful application of this is to conditionally apply a function to a value based on some predicate. In this challenge, you will be asked to write a function that takes a predicate function and a function to apply when the predicate is true, and returns a new function that applies the function when the predicate is true.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") subgraph Lab Skills python/comments -.-> lab-13742{{"`Apply Function Conditionally`"}} python/conditional_statements -.-> lab-13742{{"`Apply Function Conditionally`"}} python/tuples -.-> lab-13742{{"`Apply Function Conditionally`"}} python/function_definition -.-> lab-13742{{"`Apply Function Conditionally`"}} python/lambda_functions -.-> lab-13742{{"`Apply Function Conditionally`"}} end

Apply Function When True

Write a function called when that takes two arguments: a predicate function predicate and a function to apply when_true. The when function should return a new function that takes a single argument x. The new function should check if the value of predicate(x) is True. If it is, the new function should call when_true(x) and return the result. Otherwise, the new function should return x.

def when(predicate, when_true):
  return lambda x: when_true(x) if predicate(x) else x
double_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2)
double_even_numbers(2) ## 4
double_even_numbers(1) ## 1

Summary

In this challenge, you have written a function that conditionally applies a function to a value based on some predicate. This is a useful technique for creating more flexible and reusable code.

Other Python Tutorials you may like