Sentinels and Random Numbers
Here's another example of a loop where the number of iterations is unknown in advance. Suppose a program computes a sum of a set of inputs given by the…
A sentinel-controlled loop
Here's another example of a loop where the number of iterations is unknown in advance. Suppose a program computes a sum of a set of inputs given by the user. The user presses enter to quit. We don't know when the user finishes entering the inputs. Instead of a for loop, a while loop is more appropriate.The empty string is the sentinel: a value that means stop rather than a value to process. Pressing ENTER without typing anything is what produces it, which is why the condition tests data != "" rather than testing a number.
Random numbers
In some situations we like to be able to simulate randomness. For example, we might toss a coin or roll a die.Python's random module contains many functions to do this. The function randrange() is easy to use since it is similar to the range() function we used in for loops. We must first import the random module to access its code. This is done using the statement import random.
randrange(start, stop, step) generates a random integer beginning with start (including) and ending with stop (not including) with step.
Looping until enough events
Write a segment of code that prints out a sequence of random numbers from 1 to 100. Stop once exactly 5 prime numbers have been printed.Note that we don't know how many iterations we need to get 5 prime numbers. This is an indefinite loop. It's better to use a while loop.