Search code examples
pythonpython-docx

how to take user input to let the user specify which aspect of a python program they want to access


Currently working on some python (version 3.10.4) code on PyCharm (Community Edition 2021.3.3) using the python-docx library (version 0.8.1.1), that allows to check the layout specifications of a Word document. These specifications include paper size (if A4 or not), page orientation (if portrait or not) and page margins (if Normal margins or not).

The code structure allows the user to access specific parts of the program based on a numerical input. Entering 1 will access the whole program (which conducts all specification checks), entering 2 will the access the paper size program only, entering 3 will the access the page orientation program only and entering 4 will the access the page margins program only. These functionalities work as required.

My question is whether it is possible in python to let the user input a combination of numerical inputs to access a combination of programs. And these combinations cannot be predicted (in this case it can be, but in instances where there are many options this seems impossible). For example entering 2 and 3 will run the just the paper size and page orientation programs.

I have tried with the following code to account for this scenario (only a general logic is shown), but it only seems to execute the code associated with the first number and not all specified numbers:

x, y, z = input(" Enter number to access a program: ")

if x == '1' or y == '1' or z == '1':
    # if x or y or z == 1 run the complete program

elif x == '2' or y == '2' or z == '2':
    # if x or y or z == 2 run the paper size program

elif x == '3' or y == '3' or z == '3':
    # if x or y or z == 3 run the page orientation program

elif x == '4' or y == '4' or z == '4':
    # if x or y or z == 4 run the page margins program

else:
# print this if a number from 1-4 was not entered
print("Invalid x")

The original code is a bit lengthy so I will not be adding it here, but a general layout of the logic is shown below. Any form of help would be appreciated. If there are any questions about the code, please ask.

x = input(" Enter number to access a program: ")

if x == '1':
    # if x == 1 run the complete program

elif x == '2':
    # if x == 2 run only the paper size program

elif x == '3':
    # if x == 3 run only the page orientation program

elif x == '4':
    # if x == 4 run only the page margins program

else:
# print this if a number from 1-4 was not entered
print("Invalid option") 

Solution

  • The input is a string, so you can conveniently use the in operator to check if it contains certain digits, provided that you have only single-digit access codes. You can use a set operation, as shown below, to check if the input contains at least one valid digit. If I understand you correctly, the logic should be like this:

    input_string = input(" Enter number to access a program: ")
    
    if set(input_string).intersection(set('1234')) == set():
        # print this if a number from 1-4 was not entered
        print("Invalid x")
    
    elif '1' in input_string:
        # run the complete program
    
    else:
        if '2' in input_string:
        # run the paper size program
    
        if '3' in input_string:
        # run the page orientation program
    
        if '4' in input_string:
        # run the page margins program
    

    Edit: If the access codes can have more than one digit, you will need to split the input string. To have more control over the order of execution, you could use a dictionary mapping the access codes to the names of the subprograms (assuming these are Python functions). For example:

    def paper_size():
        print("Running paper size program.")
    
    def page_orientation():
        print("Running page orientation program.")
    
    def page_margins():
        print("Running page margins program.")
    
    def print_page():
        print("Printing page.")
    
    prompt = """Enter numbers to access programs, separated by spaces.
    1: Run the complete program.
    2: Paper size
    3: Page orientation
    4: Page margins
    11: Print page\n\n"""
    
    valid_codes = {1, 2, 3, 4, 11}
    subprogram = {2: paper_size,
                  3: page_orientation,
                  4: page_margins,
                  11: print_page}
    
    input_string = input(prompt)
    requested = input_string.split()
    
    for i, s in enumerate(requested):
        try:
            requested[i] = int(requested[i])
        except ValueError:
            print(f"Invalid input: {s}")
            break
        try:
            assert requested[i] in valid_codes
        except AssertionError:
            print(f"Invalid code: {s}")
            break
    
    if 1 in requested:
        print("Running complete program.")
    
    else:
        for i in requested:
            subprogram[i]()