Python - Lambda Week: Building and Asking for Functions
Welcome to Python Week! This we we're going to cover calculus and the keyword lambda.
Note: All Python scripts presented this week were created using a TI-NSpire CX II CAS. As of June 2022, the lambda keyword is available on all calculators (in the United States) that have Python. If you are not sure, please check your calculator manual.
Lambda - Introduction
The key word lambda allows us to define a one-line function in Python program for internal use. Keep in mind, this is different from the define (def-return) structure, where we can define multiline functions and can be used to be imported into other programs or the shell.
I briefly introduced lambda last September: https://edspi31415.blogspot.com/2021/09/calculator-python-lambda-functions.html
The syntax for lambda is for one argument:
fx=lambda var:define f(var) here
And we can use fx(var) to calculate the lambda function.
We can use more than one argument, and the syntax looks something like this:
fx=lambda var1, var2, ...:define f(var1, var2, ...)
We use fx(var1,var2,...) to recall and calculate.
Keep in mind, a lambda function can accept many arguments, but can only return one answer. The script lambdabuild.py shows a short demonstration of the lamdba key word:
lambdabuild.py: Build a lambda function
from math import *
# build a lambda function
# lambda can have more than 1 input, but
# must have only 1 output
Getting User Input
We can ask for a user function by the lines:
This can be combined in one line:
fx=eval("lambda x:"+input("f(x) = "))
The eval function changes a string to an expression to be evaluated. This is great because we can use eval to change strings to make lambda functions and ask for input of numerical expressions including pi (assuming the math module is imported).
lambda2.py: Asking for a function
# Math Calculations
from math import *
# ask the user to define a function
# input defaults as a string
print("The math module is imported.")
print("Use eval for allow for numeric expressions,")
f=eval("lambda x:"+input("f(x) = "))
# ask for three inputs
# use eval to allow for expressions
# print results
print("Here are your results:")
All original content copyright, © 2011-2022. Edward Shore. Unauthorized use and/or unauthorized distribution for commercial purposes without express and written permission from the author is strictly prohibited. This blog entry may be distributed for noncommercial purposes, provided that full credit is given to the author.