Search⌘ K
AI Features

Sentinel Loops

Explore sentinel loops in Python, focusing on using sentinel values to manage loop termination when the iteration count is unknown. Learn syntax, common errors, and practice examples to build confidence in programming while loops with sentinel values.

The sentinel value

Sometimes, a loop doesn’t have a fixed number of repetitions. Instead, an indicator value stops the loop. This special value is called the sentinel value. For example, we don’t know how much data is in a file without reading it all. However, we know that every file ends with an end-of-file (EOF) mark. So, the EOF mark is the sentinel value in this case.

Note: We should select a sentinel value that’s not expected in the normal input.

The while loop

We use the while loop when the termination of the loop depends on the sentinel value instead of a definite number of iterations. As a simple example, we want to display the reverse sequence of digits in a positive integer value input by the user.

a = int(input("Enter the number:")) # Taking input in variable a
while a > 0: # This loop will terminate when the value of a is not greater than 0
  print(a % 10,end="" )
  a //=10 # Dividing a by 10 and assigning the result to variable a
print()
Reverse of an integer value

In the program above:

  • In the first line, we take input from the user.
  • The loop statement, while, is followed by a conditional expression and then a colon :.
  • The next two statements are in the body of the loop indicated by the indentation.
  • The body of the loop executes if the condition expression a > 0 is true. This statement tests the condition before entering the loop. Such a loop is called a pretest loop.
  • The loop terminates when the condition evaluates to false.
  • In the body of the loop, the first statement displays the value of the units position using the modulo operation.
  • The second statement strips that unit’s value from a using integer division.
...