2014-09-28 86 views
0

您將如何實現一個菜單,用戶必須在繼續之前選擇第一個選項?我想用while循環其中:使用while循環的菜單

menu= '''0 - enter number 
    1 - do something with number 
    2 - do something else 
    3 - do something else 
    4 - quit''' 

    user_option =() 
    while user_option!=4: 
     elif user_option==0: 
      num = int(input("What is your number? ")) 
     elif user_option == 1: 
       do something 
     elif user_option==2: 
       do something 
     elif user_option==3: 
       do something 

基本上我想弄清楚辦法有地方如果用戶選取選擇1 2或3的一種方式,那麼它會說:「挑選項零一」如果它先選擇零選項,那麼該程序將起作用。

回答

0

你可以嘗試一些東西,就像用戶選項不等於0打印「選擇第一個選項0」,然後在while循環之外是程序。我不知道太多的Python,所以我不能幫助語法,但這是我如何在Java中做到這一點。

0

您應該爲此使用cmd模塊。代碼應該是這個樣子,

import cmd 

class MyCmd(cmd.Cmd): 
    """Simple command processor example.""" 

    def do_0(self, line): 
     """enter number""" 
     num = int(input("What is your number? ")) 

    def do_1(self, line): 
     """do something with number""" 

    def do_2(self, line): 
     """do something else""" 

    def do_EOF(self, line): 
     # Return from the shell 
     return True 

    def postloop(self): 
     print 

if __name__ == '__main__': 
    MyCmd().cmdloop() 

當你運行它你會得到這樣的事情,

(Cmd) help 

Documented commands (type help <topic>): 
======================================== 
0 1 2 

Undocumented commands: 
====================== 
EOF help 

(Cmd) help 0 
enter number 
(Cmd) help 2 
do something else 
(Cmd) help 1 
do something with number 
(Cmd) 0 
What is your number? 32 
(Cmd) 
+0

是否有一個更簡單的方法使用嵌套while循環來做到這一點? – user300 2014-09-29 01:48:24

+0

這將重新發明車輪。除非你是新手,否則你不應該建立一些已經存在的東西 – 2014-09-29 15:23:23

0
zero_selected = False 

while 1: 
    num = input("Custom message: ") # for python2.x, for python3.x 
    if num == 4:      # you'll probably need an int() wrapped around 
     break # or quit code 

    if num == 0: 
     n = input("Message ")  # or int(input("Message")) for python 3.x 
     zero_selected = True 

    if zero_selected: 
     if num == 1: 
      # do stuff 
     elif num == 2: 
      # do other stuff 
     elif num == 3: 
      # do something else 
     else: 
      # invalid input case 
    else: 
     print "Pick option zero first" 
     continue # if you have some other cases 

我真的很喜歡使用的while 1如果你能真正理清所有可能的場景並處理它們。