Python Program - Display Powers of 2 Using Anonymous Function
www.igiditfea.com
Here's a program to display powers of 2 using an anonymous function in Python:
# define the number of terms num_terms = 10 # use anonymous function to calculate powers of 2 terms = list(map(lambda x: 2 ** x, range(num_terms))) # print the terms for i in range(num_terms): print("2 raised to power", i, "is", terms[i])
In this program, we first define the number of terms we want to display (in this case, 10). We then use an anonymous function (also known as a lambda function) to calculate the powers of 2. This function takes an argument x
and returns 2 ** x
. We apply this function to a range of num_terms
using the map
function, which creates a list of the resulting values.
Finally, we iterate over the list of terms and print each one with a message indicating the power it represents.