[Tutor] Calculate 4**9 without using **
Alex Kleider
akleider at sonic.net
Sat Mar 4 21:07:23 EST 2017
On 2017-03-04 08:17, Sri Kavi wrote:
> I'm a beginner learning to program with Python. I'm trying to explain a
> solution in plain English. Please correct me if I'm wrong.
> Create a function that takes base and exponent as arguments.
Is seems that you are facing the same problem as Tasha Burman.
Sounds like an assignment meant to exercise your use of iteration.
i.e. ** and various built in power functions that have been suggested
are out of bounds.
> In the body of the function:
> set a result variable to the base.
def pwr(base, exponent):
....
res = base
...
> User a for-loop with a range of 1 to the exponent.
for i in range(begin, end): # The challenge is to pick begin and
end.
end will be a function of exponent but not exponent itself.
I don't think 1 is a good choice for begin.
Picking the correct begin is related to dealing with the following:
What if any of the following are true, and what should be done in each
case?
if exponent ==1: .....
if exponent = 0: .....
if exponent < 0: .....
Each of the first two might deserve its own return statement.
>
> With each iteration, set the result to the product of result times
> base.
res *= base # same as res = res * base
It's a fun little exercise- a bit more complex than I initially thought
it would be.
Please share your implementation.
More information about the Tutor
mailing list