Kodeclik Blog


Python pow()

Python’s pow() is a handy function for exponentiation operations. For instance, to compute 2^4, you can do:
Note that the first argument is the base and the second is the exponent. The output is:
To see how rapidly powers grow, try this program:
The output is:

Usage of pow()

pow()’s two arguments can be any integers, floats, or even negative numbers. See for instance:
The output is:
Let us dissect what is happening. The first line simply computes 2^1 which is just 2. The second line is raising 2 to the negative power of 1, which is really shorthand for ½, or 0.5. The third line is using 0.5 as the exponent which means it is really computing the square root of the base, i.e., square root of 2. The fourth line is similar to the third line but because it is a negative exponent, it is the reciprocal of the previous value. Finally, the fifth line is raising a negative number to an even exponent, so the result is positive.

pow() with a third parameter

Consider the program:
Here the first two arguments are used to compute 10^1 or just 10. We are then applying the modulus operator repeatedly on 10 with a range of arguments, from 1 to 9. The output is:
To decipher what all these numbers mean, here is a handy print statement you can substitute in place of the earlier one:
The output is:
This is now self-explanatory. For the numbers that are factors of 10, i.e., 1,2,5 we get a remainder of 0 when this number is used as the third argument of pow(). For others, you can verify that the function is working as intended.

pow() with complex numbers

Incidentally, depending on the arguments given to pow() the result could be a complex number. Consider for instance finding the square root of negative 1, which is the imaginary number “i” (denoted by “j” in electrical engineering and in Python circles). Here is a program to compute it:
The output is:
Wow - what does this mean? Note that the result is a complex number which has a real part and an imaginary part. The real part is 6.123233995736766e-17, an exceedingly small number that can be taken to be zero. The imaginary part is the “+1j” part which here denotes square root of -1.
Similarly if we try:
We will get the numerical approximation to “2j”, like so:
If you liked pow(), you will also enjoy learning about Python's double slash operator.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2022. All rights reserved.