Does 'return' works as 'break'?
No. What functions as a break
is that you have a condition (y > 1
) which will be essentially reduced to being false
at some time, since for every iteration of the loop, you decrement the conditional variable (so no matter how big a value it is, it's bound to become less than one at some point, making the conditional expression evaluate to false
).
At that point, return
just returns the result of the computation that has happened in the loop, which is being stored in powered
.
Apart from that, you have a very beautiful problem that can be solved using recursion. You can do that and use Python's version of the C ternary operator (A if B else C
), in order to arrive to a very beautiful and pythonic solution, that I consider to be very much in the spirit of computer science:
def pow(x, y):
return 1 if y == 0 else x * pow(x, y - 1)
This may look weird for a newbie, but it's actually easier if you understand what happens. Let's go through it:
First of all, let's see the nature of a power
computation: \$2^5\$ is essentially \$2 * 2 * 2 * 2 * 2\$. Our code produces the following call stack:
pow(2, 5)
2 * pow(2, 4)
2 * 2 * pow(2, 3)
2 * 2 * 2 * pow(2, 2)
2 * 2 * 2 * 2 * pow(2, 1)
2 * 2 * 2 * 2 * 2 * pow(2, 0)
2 * 2 * 2 * 2 * 2 * 1 # because of our base case that the condition eventually get's reduced to
2 * 2 * 2 * 2 * 2
2 * 2 * 2 * 4
2 * 2 * 8
2 * 16
32
I do not know if the above is super useful to you, because that depends on your programming skills at this point. But since you mentioned you already know C, I reckoned that you may be already exposed to algorithmic concepts such as recursion and I thought that demonstrating this syntax and the concept in a nice solution might help you understand how powerful this concept is and how you could utilize it in your programs.