2014-03-30 26 views
1

這可能是一個非常非常基本的愚蠢問題,但我無法管理如何做到這一點;我有這樣的菜單(在Python 3):啓動一個模塊到Python菜單

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') 

(是的,它是寫在法國的方式),我想,當用戶輸入「1」作爲一個選擇,我想使它啓動我在同一個.py文件中創建的函數,例如def thefunction():

我想要菜單在用戶輸入'1'時啓動thefunction()函數。我嘗試了很多東西,比如(從if choix=='1')函數(),導入函數(),從file.py導入()...並沒有任何作用。我沒有找到正確的方法來做到這一點,我猜?

回答

1

您收到了什麼錯誤?代碼正在自行開發。

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") 

只要你在調用它之前在某個時候聲明瞭函數,你的代碼就可以工作。你的代碼沒有問題,但要確保你的函數已經被正確聲明。

乾杯,

+0

非常感謝,它實際上是隻是因爲我在菜單後面寫了def函數;之前我複製並粘貼了它,它像魅力一樣工作;謝謝! –

0

我裹碼了一點,所以它更容易使用(既Python 2和兼容3)。

這是使得它的工作機器,你可以剪切和粘貼:

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() 

,然後你可以使用它像這樣:

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() 
+0

感謝您的時間!實際上我只是在菜單後面寫了def函數,這就是爲什麼它沒有工作;必須寫下去。謝謝! –