Is it possible to create a menu with difrent functions and different inputs?

Question:

I’m new to Python, with very limited knowledge. I’m trying to learn hands on.

I’m using argparse to get input when calling my main program.

Them I’d like to have a menu, let’s say with 3 options:
1 – execute function x
2 – execute function y
3 – exit

I’ve managed to do this using some examples from the net with

if operation == '1':
    function_x()

and so on… When I select "1" I’m going to call my function x.

There, I’d like to get more inputs from the user.
Is it possible to have something similar to the program input arguments, but to have input arguments/parameters specifically for the function associated with my option in the menu? Function x has completely different arguments/parameters than function y.

I know that I can create a list with many optional input arguments with argparse, but the idea that I have, is that the user when starts the program doesn’t know which options he will need to use. He may run function x, and based on the result, he will need to run function y or z and the parameters that he will need for those functions will vary depending on the result of function x.

Does this makes sense? Is it possible?

Thanks

Asked By: TugaIntel

||

Answers:

One approach could be to have function_x be in charge of prompting for its own arguments. For example:

def main_menu():
    options = {
        "1": function_x,
        "2": function_y,
    }
    while True:
        print("Pick an option:")
        for opt, func in options.items():
            print(f"{opt}) {func.__name__}")
        try:
            options[input()]()
        except KeyError:
            print("That's not a valid option!")

def function_x():
    x = input("What do you want to use for x? ")
    print(f"ah yes, {x} will make a fine x!")

def function_y():
    y1, y2 = input("First Y? "), input("Second Y? ")
    print("Here they are in sorted order:", *sorted([y1, y2]))

if __name__ == '__main__':
    main_menu()
Answered By: Samwise
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.