Python Program to Display Powers of 2 Using Anonymous Function


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

Powers of 2 are a sequence of numbers that are obtained by repeatedly multiplying 2 by itself. The first few powers of 2 are:


2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
2^5 = 32
2^6 = 64
2^7 = 128
2^8 = 256
2^9 = 512
2^10 = 1024

And so on.

Powers of 2 are important in computer science and information theory because computers use a binary number system, which is based on powers of 2. In binary, each digit can only be 0 or 1, and each digit represents a power of 2, starting from 2^0 (which is 1) and increasing by powers of 2. For example, the binary number 1010 represents:

1 x 2^3 + 0 x 2^2 + 1 x 2^1 + 0 x 2^0 = 8 + 0 + 2 + 0 = 10

Powers of 2 are also used in other areas of mathematics and science, such as in physics and engineering, where they are used to represent quantities that grow exponentially, such as the size of a population or the intensity of a signal.


Python Code :

The below Python program that uses an anonymous function (also known as a lambda function) to display the powers of 2:


# define the range of powers to display
n = 10

# define the anonymous function to calculate the powers of 2
powers_of_2 = lambda x: 2 ** x

# use a for loop to display the powers of 2
for i in range(n):
    print(powers_of_2(i))

In this program, we first define the range of powers to display as n = 10. You can change this value to display more or fewer powers of 2.

Next, we define an anonymous function called powers_of_2 that takes an input x and returns 2 ** x. This function calculates the powers of 2 for any input value of x.

Finally, we use a for loop to iterate through the range of values from 0 to n-1, and for each value of i we call the powers_of_2 function with i as the input and print the result.

When you run this program, it will output the following:


1
2
4
8
16
32
64
128
256
512


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co