This. def power(base, exponent): """ Returns base**exponent. """ if exponent < 0: base = 1 / base exponent = abs(exponent) result = 1 for _ in range(exponent): result *= base return result
On Mon, Mar 6, 2017 at 11:53 PM, Alex Kleider <aklei...@sonic.net> wrote: > 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.) > _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor