Dialogue with the user at the command line: the Yes/No program in Python

by Alex
Dialogue with the user at the command line: the Yes/No program in Python

Dialogs are used everywhere, an example would be any application on your computer (browser, video players, word processors, etc.). The Yes/No dialog is a simple example of a command-line dialog program.

What is a dialog program and why it is needed

A program that involves interaction with the user is called a dialog (interactive) program. Typing text, clicking buttons, and downloading files are all ways in which the user interacts with the application. Dialogue between the program and the user is an important part of any project. If a program works with only strictly defined data, it doesn’t make any practical sense.

The Yes/No dialog program in Python

Dialogue can be done either through the GUI or through the command line. Both can be implemented with Python, but communicating with the user through the terminal has a simpler implementation and requires less code. The gist of such a program is simple: the user answers questions by typing Yes – yes, or No – no into the console. Do not think that nowadays it is important to interact with a program only through the graphical interface, the command line is also used.

For example, the Linux operating system often installs programs through the command line. The system may pause the process and ask the user if he wants to continue installing “Do you want to continue [Y/n]?”, he must type Y to confirm, otherwise N.

It is clear that the command line dialog is more often used by advanced users or technicians who are not intimidated by the text command mode. The Yes/No console dialog is especially relevant, because it doesn’t require you to implement a graphical interface, which may be useless for certain tasks.

Implementing the Yes/No dialog feature in Python

Writing a console dialog program in Python is very easy, but you need to consider and think about some nuances, such as incorrect input from the user. Yes/no can easily be replaced with Yes/No, but let’s follow generally accepted standards and use English.

Function declaration

We will put all the logic of the dialog program into a separate function and declare it as follows

def yes_no_dialog(question, default_answer="yes"):

Here the arguments mean the following:

  • question is the question that is displayed on the command line and to which the user must give a “yes” or “no” answer.
  • default_ answer is an optional parameter that will be used if the user does not type an answer, but simply presses Enter.

Initial settings

Assume that the user can enter not only “yes”, but also “y” or “ye”. Handling each option with conditional if – else statements is impractical and requires a lot of unnecessary code. That’s why let’s put all answers in the dictionary:

answers = {"yes":1, "y":1, "ye":1,
           "no":0, "n":0}

default_answer allows you to specify a preferred answer option, but it is not obvious to the average user. Depending on contents of default_answer we will output a corresponding hint:

if default_answer == None:
    # if default_answer is not defined
    tip = " [y/n] " # print both letters in lowercase
elif default_answer == "yes":
    # if the default answer is "yes"
    tip = " [Y/n] " # Print Y
elif default_answer == "no":
    # If the default answer is "no"
    tip = " [y/N] "
else:
    raise ValueError(f'Invalid value: {default_answer = }')

When entering the default_answer argument we can also make a mistake, so in the else block we raise an exception that points to an invalid input.

The main loop

We need to think about the following situations when the user:

  • It does not type anything, but default_answer is defined.
  • Enters the correct answer.
  • Enters the wrong answer.

It is better to use an infinite loop for implementation. First you need to display the question and the hint and then get the user’s input:

while True:
    print(question + tip + ": ", end="")
    user_answer = input().lower() # bring to lower case

Read more about input and output here. Now input needs to be handled so that correct input will exit the loop and incorrect input will start the loop all over again:

# If default_answer is defined and the user has not entered anything
if default_answer is not None and user_answer == '':
    # Exits the function, returning the value corresponding to default_answer
    return answers[default_answer]
# If user has entered the correct answer
elif user_answer in answers:
    return answers[user_answer]
# if the answer is wrong, print the message and go on in the loop
else:
    print("Please enter yes/y or no/nn")

The full function code

Putting everything together, we have a ready to use function for a dialog with the user:

def yes_no_dialog(question, default_answer="yes"):
    answers = {"yes":1, "y":1, "ye":1,
        "no":0, "n":0}
    if default_answer == None:
        tip = " [y/n] "
    elif default_answer == "yes":
        tip = " [Y/n] "
    elif default_answer == "no":
        tip = " [y/N] "
    else:
        raise ValueError(f'Invalid value: {default_answer = }')
    while True:
        print(question + tip + ": ", end=")
        user_answer = input().lower()
        if default_answer is not None and user_answer == ''
            return answers[default_answer]
        elif user_answer in answers:
            return answers[user_answer]
        else:
            print("Please enter yes/y or no/nn")

Example program

Suppose the function gets some questions from a file, the results of answers are written to another file, then the program code would look like this

a = open("qst.txt", "r", encoding="utf-8") # open file for reading
results = []
for lines in a: # we read the file line by line
    # call our function for each line and put
    # value in the list result
    results.append(yes_no_dialog(line.strip()))
a.close()
b = open("results.txt", "w") # open file for writing
for elem in results:
    # Write each element of the list to the file, separated by a space
    b.write(str(elem) + " ")
b.close()

Use the strip string method to remove the extra characters. Before you run your Python program, don’t forget to prepare a qst.txt file with questions like this:

The first question
The second question
The third question

For Russian letters are displayed correctly – correctly specify the encoding when you open the file. In my case, it is encoding="utf-8". The result will be the following:

First question [Y/n] : Y
The second question [Y/n] : no
Third question [Y/n] : yes

Thecontents of the result file will be as follows:

1 0 1

Related Posts

LEAVE A COMMENT