All high-level programming languages include mathematical operations. Math helps create models, simulations, and calculation-based applications. One crucial operation is raising a number to a power or exponentiation.
Powers are a quicker way to write iterative multiplication. Python offers two ways to calculate the power of a number.
This guide shows how to use the power operator and function in Python with examples.
- Python version 3 installed.
- A code editor to write the code.
- An IDE or terminal to run and test the code examples.
Python Power pow() Function Syntax
The power function is a built-in method for calculating powers and modulo (division remainder). The method performs a different calculation depending on the number of variables provided.
The syntax for the command is:
pow(base, exponent, modulo)
The function takes two or three arguments. When used with two arguments, the method calculates an exponential expression. For example:
The function outputs the operation result of the
base value to the power of the
Python Power pow() Example
To use the Python
pow() function, provide two values directly or through variable reference. The example below demonstrates how the use the
print(pow(2, 3)) print(pow(5, 2)) base = 10 power = 2 print(print(pow(base, power)))
Each line does the following:
- The expression in line 1 calculates
2to the power of
3, which is equivalent to
- The second expression in line 2 calculates
5to the power of
2, which is the same as
- The final expression in line 5 calculates
10to the power of
2using variables from lines 2-3.
The program prints the calculated result of all three operations.
Python Power ** Operator Syntax
** operator is a built-in operator for calculating powers in Python. The syntax for the operator is:
The operator calculates the exponential expression directly and outputs the result.
** operator works in the same way as the
Python Power Operator Example
Use the Python power operator directly on two numbers or variables. For example:
print(2**3) print(5**2) base = 10 power = 2 print(base**power)
Each line performs a different exponential operation using the
** operator. The program prints the result for each power operation to the console.
After reading this guide, you know two ways to perform exponentiation in Python: the
pow() method or the
** power operator.
For more Python guides, see our comprehensive guide on Python comments.