[Tutor] Calculate 4**9 without using **
Alex Kleider
akleider at sonic.net
Mon Mar 6 13:23:41 EST 2017
On 2017-03-05 23:52, Sri Kavi wrote:
> This version deals with both negative and non-negative exponents in a
> single loop. I like this.
> def power(base, exponent):
> """ Returns base**exponent. """
> if exponent == 0:
> return 1
> else:
> result = 1
> for _ in range(abs(exponent)):
> result *= base
> if exponent < 0:
> return 1 / result
> else:
> return result
>
> I'm learning a lot. Thank you for being so helpful.
I have enjoyed this little exercise, so thank you for drawing attention
to it and continuing to work at it.
Note that you don't need the 1st if/else- and even if you did, you
wouldn't need the 'else': just 'de-iondent' everything that is in its
code block.
I believe the following (your code with some deletions) will work:
def power(base, exponent):
""" Returns base**exponent. """
result = 1
for _ in range(abs(exponent)):
result *= base
if exponent < 0:
return 1 / result
else:
return result
An alternative way to deal with the negative exponent possibility is to
test for it at the beginning and if True, set base to its reciprocal and
exponent to its absolute value (no need for an else component.)
More information about the Tutor
mailing list