Is there another method to do exponentiation other than the ** operator?


Is there another method in Python to perform exponentiation other than the ** operator?


Yes, the Python math library has a pow() function which can perform exponentiation. The primary difference between the ** operator and the pow() function is that the pow() function will convert the numbers to floating point while the ** operator will not.


Then there is the way the computer does it… repeat addition.

Inputs are A and B.
To R add A and take away 1 from the B register. 
Repeat until the B register is 1. 

That gives us a * b.

>>> def a_x_b(a, b):
	r = a
	while b > 1:
		r += a
		b -= 1
	return r

>>> a_x_b(6, 7)

I’m not sure a computer will follow this simple algorithm, so am truly winging it from here…

>>> def a_xx_b(a, b):
	r = a
	while b > 1:
		r = a_x_b(r, a)
		b -= 1
	return r

>>> a_xx_b(3, 3)
>>> a_xx_b(2, 10)

Here it is, refactored into a single function …

def a_xx_b(a, b):
    r = a
    while b > 1:
        xa = r
        xb = a
        xr = xa
        while xb > 1:
            xr += xa
            xb -= 1
        r = xr
        b -= 1
    return r

Steps performed:

  • The variables in the a_x_b function were renamed by prepending their names with x.
  • The body of the a_x_b function was pasted into the a_xx_b function immediately following its call to the the a_x_b function.
  • The indentation was adjusted to accommodate the pasted code.
  • Right above where the pasting was done, assignments were made from what had been the arguments in the function call to what had been the renamed parameters of a_x_b function.
  • The return statement from the a_x_b function was replaced by an assignment of the result to the variable, r, that had originally received the result of the function call.
  • The call to the a_x_b function was removed.

Hello, i would like to ask this. Is it normal for a new coder with no background experience like me to find it difficult to cope with understanding this type of code? I get along really good with functions but this one really blew my mind. I understand how function a_x_b(a,b) works, but a_xx_b(a,b) gave me a really hard time getting it. Is it bad or should I go on with my ongoing Python 3 course and revisit it once i have the equivalent experience?

Yeah, this one did require some concentrated thinking on my part.:sweat_smile:

thank you, now i feel a lot better!

1 Like

how to precisely use this function ??

The lesson describes the pow() function as an alternative to writing ** in an expression.

>>> 2 ** 10
>>> pow(2, 10)

It also notes that the function returns a float; however, the above would indicate otherwise.

1 Like

I don’t understand this in longhand, never mind in code. Not something I memorized from my last maths class 30 years ago. Frustrating to be stuck trying to relearn maths within this course.