Control Structures
Last updated
Was this helpful?
Last updated
Was this helpful?
Control statements provide the facility to switch the flow of control in a program. Python provides a few control statements like if-else
, while
and for
.
if-else
is for conditional switching of the control.
for
and while
for doing something repeatedly.
Almost all programs utilize these control statements to accomplish the task at hand or to solve the given problem.
Let's demonstrate a while loop using Euclid's algorithm for finding the greatest common divisor.
The greatest common divisor (GCD) of two numbers, is the largest number that divides both of them without leaving a remainder. As given in this example from Math is Fun the greatest common divisor of 12 and 16 is 4.
An efficient way to formulate GCD was given by Euclid.
To find the GCD of A, B, given A > B.
If A divided by B is 0, then GCD is B.
Otherwise, calculate Reminder R of A divided by B. (R = A mod B).
Find out GCD(B, R), that is subsitute B for A, R and R for B, go to step 1 which calculates GCD.
The explanation of this euclid algorithm explained well by Alexander Bogomolny in his cut the knot
Problem Credits: Think Python Exercise, SICP, and Euclid's Algorithm.
We will skip past the undefined NameError
and for an undefined gcd
function and write a gcd
function that returns a 0.
Exercising this test, we get the AssertionError.
Let's follow the Euclid's algorithm to fix the tests.
The program follows our understanding of the Euclid's algorithm.
And exercising the test showed that the program worked properly.
There are a few avenues for refactor in the above code. The first one is, return statement.
If the variable R
is 0, then our while
loop will exit and we could utilize that fact to return our result.
And then, if we observe carefully, the first statement can be removed. Because we are calculating A % B
and comparing it with 0.
Could we refactor this further? Yes, our verification for for step 1 can be made in the while statement itself.
Exercising this will result in an Error.
The error indicates that we use the variable R
ahead of its assignment. Our logical usage is incorrect as well. We can correct the code as per the algorithm above.
And exercise this code results in a success.
At this moment, I decided to stop because any further refactoring, like calculating A % B
only once will lead to edge cases, which can be confusing.
The code follows our algorithm to the dot, and easy to remember.
The final solution looks like this. And this works for number in any order.