Here's the question you clicked on:
NPAA77
Python MOOC question. I'm doing: Exercise 1.8 – For & While Loops 3. Write a program using a for loop that calculates exponentials. Your program should ask the user for a base base and an exponent exp, and calculate baseexp. I'm not sure where the for loop comes into play, as described in the assignment. Maybe i'm reading the assignment wrong? This is what I got: b=input('Enter base: ') n=input('Enter exponent: ') bn=b**n print bn What is the loop supposed to do? Are you supposed to be able to run the program over and over again?
From a design standpoint you can use loops to do the exponents math. For example if you wanted to get 5^3 int base = 5, exponent = 3; while(exponent > 0) { base *= exponent; //equivalent to base = base*exponent exponent--; } That's c++ but I think you can get the idea from that
For exercise 1.8, they want you to use what's sometimes called an accumulator. An accumulator is usually created prior to a loop for the purpose of accumulating a sum or a product within the loop. For a sum, the accumulator would usually be initialized to 0, and for a product, it would be usually be initialized to 1. In this problem, we are aiming for a product. If we name our accumulator "acc", we can proceed as follows, after getting the base (b) and exponent (e) from the user ... acc = 1 for i in range(e): acc *= b the accumulator (acc) will contain the result after the loop terminates.
Thank you I think I understand better now. What if I may ask is the benefit of using a for loop to calculate the exponent over using the simple code I posted? #user inputs b for base and n for exponent bn=b**n
The thing is there usually isn't a benefit. It's just an exercise in loops to get you to do something you already can do in a different way. I'd wager the built in exponent function/operator is more efficient than a loop
@bibby There's a correction to your code to the following line, base *= exponent; //equivalent to base = base*exponent It could be: answer *= base //Inital value of answer = 1 Regards
Hmm thanks for the check. I can't think of a reason why it needs an initial value though. Is it in case you do say x^0?
Since a new variable is being used..We can't perform: answer = answer * base unless 'answer' is initialised first. And we need a new variable (similar to the accumulator mentioned by @AppylPye ) to store the temporary values of the loop..Hence can't reuse the variable 'base'. If 'answer' is set to 1, the loop needs to run three times to get the right answer. if 'answer'is set to the value of base (5 in this case), the calculation would require only 2 iterations of the loop (but the code will have to be tweaked a bit)
Ah, thanks for the correction again. I think I'm gonna undo my medal and give it to you. How embarrassing~ :p