2014-02-25 54 views
0

我正在處理部分程序,該程序向用戶提供了3個選項的菜單。我想讓用戶進入他們的菜單選擇(1-3),之後菜單再次出現,並允許用戶輸入另一個選擇並重復該過程總共n次,用戶在菜單之前也輸入該選擇。允許用戶從菜單中選擇用於循環的選項

該程序只是連續3次打印菜單,而不是n次單獨的迭代,但我不知道如何解決這個問題。

n = int(input('Please enter the number of iterations:')) 

for i in range(0,n): 

    print('Enter 1 for choice 1\n') 

    print('Enter 2 for choice 2\n') 

    print('Enter 3 for choice 3\n') 

    choice = int(input('Enter your choice:')) 

    if (choice == 1): 

    .... 
    .... 

    else: 
     print('Invalid choice') 

回答

6

把你的代碼來處理循環內的選擇:

n = int(input('Please enter the number of iterations:')) 

for i in range(0,n): 

    print('Enter 1 for choice 1\n') 

    print('Enter 2 for choice 2\n') 

    print('Enter 3 for choice 3\n') 

    choice = int(input('Enter your choice:')) 

    if (choice == 1): 

     .... 
     .... 

    else: 
     print('Invalid choice') 
+0

太好了,謝謝! – user2913067

1

縮進下面的一段代碼,4位到右:

if (choice == 1): 
    ... 
    ... 
else: 
    print('Invalid choice') 

但是,如果我可以建議更好地實現您正在嘗試執行的操作,然後定義一個可處理非數字用戶輸入的函數,另外,在for循環之外拍攝這些照片:

def getUserInput(msg): 
    while True: 
     print msg 
     try: 
      return int(input(msg)) 
     except Exception,error: 
      print error 

n = getUserInput('Please enter the number of iterations:') 

print 'Enter 1 for choice 1' 
print 'Enter 2 for choice 2' 
print 'Enter 3 for choice 3' 

while n > 0: 
    choice = getUserInput('Enter your choice:') 
    if choice == 1: 
     ... 
     n -= 1 
    elif choice == 2: 
     ... 
     n -= 1 
    elif choice == 3: 
     ... 
     n -= 1 
    else: 
     print 'Invalid choice' 
1

只是爲了好玩:我已經重寫了這個介紹一些更高級的想法(程序結構,使用enumerate(),一等功能等)。

# assumes Python 3.x 
from collections import namedtuple 

def get_int(prompt, lo=None, hi=None): 
    while True: 
     try: 
      val = int(input(prompt)) 
      if (lo is None or lo <= val) and (hi is None or val <= hi): 
       return val 
     except ValueError: # input string could not be converted to int 
      pass 

def do_menu(options): 
    print("\nWhich do you want to do?") 
    for num,option in enumerate(options, 1): 
     print("{num}: {label}".format(num=num, label=option.label)) 
    prompt = "Please enter the number of your choice (1-{max}): ".format(max=len(options)) 
    choice = get_int(prompt, 1, len(options)) - 1 
    options[choice].fn() # call the requested function 

def kick_goat(): 
    print("\nBAM! The goat didn't like that.") 

def kiss_duck(): 
    print("\nOOH! The duck liked that a lot!") 

def call_moose(): 
    print("\nYour trombone sounds rusty.") 

Option = namedtuple("Option", ["label", "fn"]) 
options = [ 
    Option("Kick a goat", kick_goat), 
    Option("Kiss a duck", kiss_duck), 
    Option("Call a moose", call_moose) 
] 

def main(): 
    num = get_int("Please enter the number of iterations: ") 
    for i in range(num): 
     do_menu(options) 

if __name__=="__main__": 
    main() 
相關問題