🐍

Understanding First-Class Functions in Python

Oct 27, 2024

Lecture on First-Class Functions in Python

Overview of First-Class Functions

  • Functions in Python are considered first-class citizens.
    • Can be assigned to variables.
    • Can be returned from other functions.
    • Can be stored in data structures like lists or tuples.
  • Use the function name without parentheses to assign or pass functions.

Assigning Functions to Variables

  • Example: Assigning a function to a variable
    • Assign a written function to variable var.
    • Call the function via the variable by passing required arguments.
    • Example: var(foo, bar) stores the return value in variable x.

Function Parameters

  • Functions can have parameters that are other functions.
    • A function parameter can be called from inside another function.
    • Allows a function to change behavior based on function arguments.

Example: Function with Function Parameters

  • Sheep Function
    • Declares a parameter sound_function.
    • Calls sound_function and stores the return value in sound.
    • Prints the sound.
  • Main Function
    • Calls sheep function with different sound functions.
    • Prints different sheep sounds based on the function passed.
    • Functions passed: bah, ram, u.

Demonstrating Assigning and Using Functions

  • Assign built-in functions to variables.
    • Example: Assign print to x and call with x('Hello').
    • Similarly, assign input to y and handle input with y().

Writing a Program with Function Parameters

  • Example program with three functions returning sheep sounds.
    • Write sheep function to accept sound function as parameter.
    • Note: Use parentheses only when calling functions.
  • Test sheep function with sound functions:
    • Results:
      • Call with bah: Prints "The sheep says bah".
      • Call with ram: Prints "The sheep says ram".
      • Call with u: Prints "The sheep says u".

Extending the Functionality

  • Add a new function without altering sheep function.
    • Call sheep with hi_there function.
    • Demonstrates flexibility - prints message based on passed function.

Conclusion

  • Function parameters allow altering behavior of functions.
  • A single function can produce multiple outputs based on the passed function parameter.
  • Demonstrates Python's flexibility and power with first-class functions.