Sentinel Value And Its Uses In Python

Here we are going to learn about sentinel values in python in a detailed manner. It is a special value in python, and it is a handy one in python. Now we are going to see about what is sentinel value? Using sentinel values to terminate loops. Applications of sentinel values and iter() function with a sentinel value.

Sentinel values are a special type of value. This value allows users to know when they are sending input. So this is a value that won’t be the part of the input to be processed. It is a value that is also useful to terminate the loop.

What is sentinel value in python?

It is a special type of value that allows a different number of inputs by the user each time. A special value that isn’t a part of the input to be processed. It allows a different number of inputs each time.

How do sentinel value work in Python?

It takes some value as an endpoint. When the endpoint to given by the user. It will display the statement that the programmer gives. For example, if I am setting sentinel value as a -98 and stating goodbye! It will take any value from the user and display the value. When the user gives -98, it will display the statement goodbye!

Example for Sentinel Value in Python

SENTINEL=-99
n=int(input('Enter a number to display,-99 to quit'))
while n!=SENTINEL:
    print(n)
    n=int(input('Enter a number to display,-99 to quit'))
print('goodbye!')

First, we are setting a sentinel value as -99. Getting input from the user. If the user enters some other value as input, it will display the same. When the user enters -99, it will display goodbye! To the user.

Output

Enter a number to display,-99 to quit:78
78
Enter a number to display,-99 to quit:-90
-90
Enter a number to display,-99 to quit:-99
goodbye!

Recommended Reading | 11 Powerful Methods to Iterate Through List in Python

Sentinel Controlled loop

score_of_the_player = int(input("Enter a score of the test -1 to stop: "))   
total_score= 0
scorecount= 0                       
while score_of_the_player != -1:                     
    total_score = total_score + score_of_the_player
    scorecount= scorecount + 1
    score_of_the_player = int(input("Enter a score of the test -1 to stop: "))  
print ("The average for the test is ",total_score/scorecount)

Getting the score of the test as input. Setting the value -1 to terminate the loop. Using while to iterate every time. It will iterate till the user gives -1. When the value hits -1, the loop will be terminated. After termination, it will display the average of the scores.

Output

Enter a score of the test -1 to stop: 80
Enter a score of the test -1 to stop: 90
Enter a score of the test -1 to stop: 100
Enter a score of the test -1 to stop: -1
The average for the test is  90.0

Semantics of Sentinels

Sentinel values are always equal to themselves. But it is not equal to another object.

Let us check this in a python compiler. Before that, we need to install a sentinel. The command to install sentinel is

pip install sentinels

Now the installation of sentinels is completed. Let us check the sentinels in the python compiler.

>>> from sentinels import NOTHING
>>> NOTHING==NOTHING
True
>>> NOTHING==7
False
>>> NOTHING=="NOTHING"
False

We can understand that sentinels are always equal to themselves by seeing the above code. First importing NOTHING from sentinels. Next, checking NOTHING is equal to NOTHING. The result is True. But when we go for another thing, it shows a result as False.

Using Sentinel as a form of Objects

sentinel = object()
def sentinel_objects():
    string = input("Enter a string , To end Enter 'stop' or 'exit' or 'done': ")
    if string == 'stop' or string == 'exit' or string == 'done':
        return sentinel
    return string
for string in iter(sentinel_objects, sentinel):
    print("You entered", string)

First, declaring sentinel. Creating a function named sentinel_objects. Getting a string from the user. Using if statement to compare the strings. If the strings are equal to the given strings, the program will be terminated. Otherwise, it will continue. And display the entered string to the user.

Output

Enter a string , To end Enter 'stop' or 'exit' or 'done': Hi this is python pool
you entered Hi this is python pool
Enter a string , To end Enter 'stop' or 'exit' or 'done': Hello
you entered Hello
Enter a string , To end Enter 'stop' or 'exit' or 'done': exit

Using sentinel as a form of class constants

class Sentinel:
    def __init__(self):
        self.SomeConstant = -1
while True:
    inp = input("Enter any number to print it.\nEnter -1 to quit\n-> ")
    if (inp.startswith('-') and inp[1:].isdigit()) or inp.isdigit():
        if int(inp) == Sentinel().SomeConstant:
            print("Loop Ended")
            break
        else:
            print(inp)

Creating a class named sentinel. Next to creating a function. Setting a sentinel value as -1. When the user hits -1, the loop will be ended. Using a while loop to iterate the values. It will iterate till the value is equal to one.

Output

Enter any number to print it.
Enter -1 to quit
-> 3
3
Enter any number to print it.
Enter -1 to quit
-> 9
9
Enter any number to print it.
Enter -1 to quit
-> -1
Loop Ended

Iterate with a Sentinel Value in Python

from functools import partial
from random import randint
sentinel=10
trigger = partial(randint, 1, 10)
print('Starting a Game....')
print('------*******-------')
for n in iter(trigger, sentinel):
    print("\U0001F600",'I am still alive :), selected', n)
print("\U0001F62D",'Oops, Game Over, selected', sentinel, 'I am DEAD! :(')

From functools importing partial. From random importing randint. Creating a variable trigger choosing a random number. Starting a game. It will iterate till it hits the sentinel value. Here we are setting the iterated value from 1 to 10 and the sentinel value as 10. Printing some emojis to make our code more beautiful.

Output

Starting a Game....
------*******-------
? I am still alive :), selected 6
? I am still alive :), selected 9
? I am still alive :), selected 6
? I am still alive :), selected 6
? I am still alive :), selected 1
? I am still alive :), selected 8
? I am still alive :), selected 2
? I am still alive :), selected 5
? I am still alive :), selected 1
? I am still alive :), selected 3
? I am still alive :), selected 7
? I am still alive :), selected 4
? I am still alive :), selected 6
? I am still alive :), selected 4
? I am still alive :), selected 4
? I am still alive :), selected 3
? I am still alive :), selected 8
? I am still alive :), selected 5
? I am still alive :), selected 7
? I am still alive :), selected 7
? I am still alive :), selected 1
? I am still alive :), selected 4
? I am still alive :), selected 2
? I am still alive :), selected 1
? Oops, Game Over, selected 10 I am DEAD! 🙁

1. What are the advantages of sentinels values?

It is used to terminate the loop. If we set some limit, then it will terminate the program when it hits the specified number.

2. Is the sentinel value is equal to any other object?

Sentinel values are always equal to themselves. But it is not equal to another object.

Conclusion

Here we came to the end of the article. We have completely learned about sentinel values in Python. We hope this is very useful and easy to understand. The above-mentioned game is beneficial. Everyone must try it.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments