Question

This might be a very very basic dumb question but I can't manage how to do that; I've got a menu like this (in Python 3):

boucle = True
while boucle:
    print('''
        1−Gestion de listes
        2−Gestion de matrices
        0-Quitter
    ''')

    choix = input('Choissisez une commande:')
    if choix == '1':
        gestionliste() 
    elif choix == '2':
        print('Gestions de matrices')
    elif choix == '0':
        boucle = False
    else:
        print('Entrée erronée:Veuillez entrez loption 1,2 ou 0')

(Yes it's written in French by the way), and I want that when the user enters '1' as a choice, I want to make it launch a function I made in the same .py file, for example def thefunction():

I want the menu to launch thefunction() function when the user enters '1'. I tried many things, such as (after if choix=='1') function(), import function(), from file.py import()...and nothing works. I've not worked out the correct way to do that I guess?

Was it helpful?

Solution

What error are you receiving? The code is working on its own.

whatever = True

def thefunc():
    print("Works!")

while whatever == True:

    print("""
        1-Whatever
        2-Whatever
        3-Whatever
    """)

    choice = input("Choice: ")

    if choice == "1":
        thefunc()

    elif choice == "2":
        print("...")

    elif choice == "0":
         whatever = False

    else:
        print("... again")

As long as you've declared the function at some point before calling it, your code should work. There's nothing wrong in your code, but make sure that your function has been declared properly.

Cheers,

OTHER TIPS

I've wrapped the code up a bit so it's easier to use (compatible with both Python 2 and 3).

this is the machinery that makes it work, you can just cut and paste it:

from collections import namedtuple

# version compatibility shim
import sys
if sys.hexversion < 0x3000000:
    # Python 2.x
    inp = raw_input
else:
    # Python 3.x
    inp = input

def get_int(prompt, lo=None, hi=None):
    """
    Prompt for integer input
    """
    while True:
        try:
            value = int(inp(prompt))
            if (lo is None or lo <= value) and (hi is None or value <= hi):
                return value
        except ValueError:
            pass

# a menu option
Option = namedtuple("Option", ["name", "function"])

def do_menu(options, prompt="? ", fmt="{:>2}: {}"):
    while True:
        # show menu options
        for i,option in enumerate(options, 1):
            print(fmt.format(i, option.name))

        # get user choice
        which = get_int(prompt, lo=1, hi=len(options))

        # run the chosen item
        fn = options[which - 1].function
        if fn is None:
            break
        else:
            fn()

and then you can use it like so:

def my_func_1():
    print("\nCalled my_func_1\n")

def my_func_2():
    print("\nCalled my_func_2\n")

def main():
    do_menu(
        [
            Option("Gestion de listes",   my_func_1),
            Option("Gestion de matrices", my_func_2),
            Option("Quitter",             None)
        ],
        "Choissisez une commande: "
    )

if __name__=="__main__":
    main()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top