oldoc63 / learningDS

Learning DS with Codecademy and Books
0 stars 0 forks source link

How to define a Python function in one line #365

Open oldoc63 opened 1 year ago

oldoc63 commented 1 year ago

A function is an object that is able to accept some sort of input, possibly modify it, and return some sort of output. In Python, a lambda function is a one-line shorthand for function.

oldoc63 commented 1 year ago
  1. The function is stored in a variable called add_two
  2. lambda declares that this is a lambda function (like def)
  3. my_input is what we call the input we are passing into add_two
  4. We are returning my_imput plus 2 (with normal Python functions, we use the keyword return)
oldoc63 commented 1 year ago

Let's write a lambda function that checks if a string is a substring of the string "This is the master string".

oldoc63 commented 1 year ago

We might want a function that will perform differently based on different inputs. Let's say that we have a function check_if_A_grade that outputs 'Got an A! If a grade is at least 90, and otherwise says you 'Did not get an A ... '

oldoc63 commented 1 year ago

This is what this code of line does:

  1. Declare lambda function with an input called grade (lambda grade:)
  2. Return 'Got an A! if this statement is true: grade >= 90
  3. Otherwise, return 'Did not get an A ...' if this statement is not true: grade >=90

Lambda functions only work if we're just doing a one line command. If we wanted to write something longer, we'd need a more complex function. Lambda functions are great when you need to use a function once. Because you aren't defining a function, the reusability aspect function is not present with lambda functions. By saving a work of defining a function, a lambda function allow us to efficiently run an expression and produce an output for a specific task, such as defining a column in a table, or populating information in a dictionary.