educative.io

What is the benefit of the advised solution over a simple loop?

The straightforward code does not consume memory on the program stack, shorter and easier to understand:

def power(x, n):
  if n < 0 and x == 0:
    raise ValueError('!')
  if n == 0:
    return 1
  if n < 0:
    return 1 / power(x, -n)

  pw = 1.0
  for i in range(n):
    pw *= x
  
  return pw

Okay, I seeā€¦ We can save some multiplications when growing x^(2^n) bottom-up.