Pow
In exponentiation, one number is multiplied by itself. This is performed with the pow method, a built-in. With two stars, we can also take exponents.
In Python, two stars and pow are equivalent. So we can use whichever one seems clearest. I feel pow is clearer, but I rarely need exponents in programs.
Here we use pow and the exponent operator. We see that 2 squared is 4 (because 2 times 2 is four). You should know this from math class
.
# Two squared is four. # ... These syntax forms are identical. print(2 ** 2) print(pow(2, 2)) # Two cubed is eight. print(2 ** 3) print(pow(2, 3))4 4 8 8
Pow
can be used with 3 arguments. The third argument is for modulo division. The result of the exponentiation operation is divided by that number. The remainder is returned.
# Compute 3 squared. # ... This is 9. # ... Perform 9 modulo 5 to get result of 4. result = pow(3, 2, 5) print(result)4
A main goal of Python is syntax clarity. Python programs are easy to read and to write. With pow, we have a choice of syntax to use.
For developers who use many exponentiation operations, two stars might be clearer. But pow is often a less-common operation. For this reason it is probably a better choice overall.