pow Example, Power Operator
This page was last reviewed on Jul 5, 2023.
Dot Net Perls
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.
First example. 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.
Here We use both the two-star operator and the pow method. We see the results of both syntax forms are equal.
# 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
3 arguments. 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.
Here We take the square of 3 to get 9. And then we divide nine by five, so we have a remainder of 4.
Note This version of pow may improve performance. But I have never needed this in a real Python program.
# Compute 3 squared. # ... This is 9. # ... Perform 9 modulo 5 to get result of 4. result = pow(3, 2, 5) print(result)
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2024 Sam Allen.