Python program to display the powers of a number

Hello friends! In this tutorial, we are going to write a simple Python program that can display the powers of an integer or number up to nth terms using an anonymous function.

Before writing our program, let’s understand the concept behind it first.

In Python, an anonymous function is defined without a name. As we know that all the other functions can be defined using the def keyword in python but for an anonymous function, we use the lambda keyword. We can conclude by saying that anonymous functions are also called lambda functions.

The syntax for lambda functions:
lambda arguments: expression

Remember that lambda functions can have many arguments but only one expression.

Now in the program below, we are using a lambda function inside the map() function to find the powers of an integer.

Note: map() is a built-in function that is used to take a function and a list in it.

Let’s have a look at our Python program given below to display the powers of a number:

num = int(input("Enter a number: "))
terms = int(input("Enter the number of terms: "))
result = list(map(lambda x: num ** x, range(terms)))

print("The total terms are: ",terms)
for i in range(terms):
    print("{} raised to power".format(num),i,"is",result[i])

So here firstly we are taking input from the user for the number and its terms. Then we are implementing the map() and lambda function to get the powers of the input number up to nth terms. Then we need to print the total terms up to which the powers of input number will get print. Lastly, we are using a print statement to display our output as shown below.

Output 1:

Enter a number: 5
Enter the number of terms: 10
The total terms are: 10
5 raised to power 0 is 1
5 raised to power 1 is 5
5 raised to power 2 is 25
5 raised to power 3 is 125
5 raised to power 4 is 625
5 raised to power 5 is 3125
5 raised to power 6 is 15625
5 raised to power 7 is 78125
5 raised to power 8 is 390625
5 raised to power 9 is 1953125

Output 2:

Enter a number: 2
Enter the number of terms: 5
The total terms are: 5
2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16

As you can see the results came out as expected. I tried to implement it in the simplest way possible. I hope you like it. If you have any doubts then please comment below.

Also, read: Screen Recorder using Python

Leave a Reply

Your email address will not be published. Required fields are marked *