[Tutor] Calculate 4**9 without using **
Alex Kleider
akleider at sonic.net
Sun Mar 5 13:50:52 EST 2017
On 2017-03-04 19:06, Sri Kavi wrote:
> I'm sorry I confused you all. I was trying to reply to Tasha Burman,
> but I
> was in digest mode and I didn't know how to turn it off. So far I've
> been
> just a lurker here. I also don't know if it's a school assignment.
> Here's
> how I would do it.
>
> def power(base, exponent):
> result = base
>
> for _ in range(1, exponent):
> result *= base
>
> return result
>
> Also, I'm still coming to grips with Python basics and programming in
> general, so I need your feedback.
>
>
Some new insites:
If you initialize result to 1 rather than base, it not only simplifies
your range parameter to (exponent) rather than (1, exponent) but ALSO
eliminates the need to treat exponent==0 as a special case.
So you've only got to deal with exponent<0.
def power(base, exponent):
""" Returns base**exponent.
As yet, does not cope with negative values of exponent.
"""
result = 1
if exponent<0:
pass # earlier posts have suggested what to do
for _ in range(exponent):
result *= base
return result
More information about the Tutor
mailing list