Definite vs Indefinite Loops
A for loop, which we discussed earlier, is an example of a definite loop: the number of iterations can be specified ahead of time by the programmer. In…
Two kinds of loop
A for loop, which we discussed earlier, is an example of a definite loop: the number of iterations can be specified ahead of time by the programmer.In some cases, however, the number of iterations can be unknown. This type of loop is called an indefinite loop. For example, a user is asked to enter a sequence of positive numbers, and can enter 0 to finish with their inputs. The number of inputs the user enters is not known in advance.
The while loop
The while loop is used to describe conditional iteration: iteration that repeats as long as a condition is true.The loop repeatedly executes its block of code as long as the condition is true. The first time the condition is false, the while loop terminates.
Definite loops
Definite loops are loops whose number of iterations can be calculated in advance.These examples call is_prime(), a helper assumed to be written elsewhere, which returns True when its argument is prime. What matters here is the loop around it, not how it works.
Indefinite loops
Indefinite loops are loops whose number of iterations is unknown.Suppose we want to write a function that returns the largest prime less than or equal to n. Here are two examples.
For a general n, the number of iterations required is unknown. In the trace above we repeatedly decrease by 1 as long as (while) the current value is not prime.