How to Raise a Number to a Power in Python



Python


In this article, we show how to raise a number to a power in Python.

Thus, you can have any base raised to any exponent.

Just a quick math review, if you have the expression, 23= 8, the 2 is the base number and the 3 is the exponent.

In Python, to replicate this, we use the following code shown below.



So we have 2, followed by **, followed by 3

The ** operator in Python means raising a number. The number preceding this operator is the base and the number following this operator is the exponent.

Just to show some variations, let's show an example code, where a user can enter a base and an exponent and we calculate the power of this calculation.

This is shown in the code below.



So we create a variable named base that accepts a number that is a float.

We then create a variable named exponent that accepts a number that is a float.

We then create a variable named answer that calculates the base raised to the exponent specified.

We then print out the answer.

Now let's create one more variation.

Let's create an expression that calculates a base raised to a power using a single mathematical expression.

Let's say we want to calculate, 23, we want to enter this in a way that can be understood easily by the user. We want to calculate a power by using the ^ operator to represent a number raised to a certain power.

Thus, to calculate 23, a user enters in, 2^3

This is shown in the code below.



So we've now created code that allows a user to type in an expression to calculate the power of some number by using the symbol ^.

So we have a variable named expression that allows a user to input an expression.

We then replace '^' with '::'. This is because Python calculates the power of a number with '::', not '^'

'^' is just better for users.

We then use a regular expression to extract the numbers from the expression. We could use other ways as well, but I chose to use regular expressions.

All of the numbers is stored in match.

match[0] will be the base number, while match[1] will be the exponent number.

match[0] ** match[1] computes the base raised to the exponent value.

And this is all that is required to raise a number to a power in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...