2014-11-24 77 views
-2

1)我有這樣的代碼迄今while循環,但我想循環僅12倍:Python中的操作菜單

print ("Please enter the 12 monthly figures") 
input ("Enter a value in the range 0 to 300:") 

我試圖for循環,但它沒有經營

2)我要創造我的代碼菜單,到目前爲止,我有這樣的:

print ("Please choose one of the following options:") 

ans=True 
while ans: 
    print (""" 
    0. Quit 
    1. Work out and display the total 
    3. Work out and display the mean 
    4. Work out and display the standard deviation 
    5. Work out and display the median 
    6. Work out and display the lowest and second lowest 
    7. Work out and display the 3 month 
    8. Work out and display the months 
    9. Work out display level 
    """) 

,但我想,讓用戶選擇一個

+1

什麼是你當前的代碼? – 2014-11-24 00:50:44

回答

0

Python顯然沒有開關/情況循環,所以你可以做的一件事就是構建一些if語句。如果你使用的是2.7,你將使用raw_input作爲用戶輸入,如果它是3.x,你只需使用輸入。

if input == 0: 
    print ("You picked zero\n") 
    ... 

等等。另外,我認爲如果你把int(input)或者你指定的輸入賦值給它,它會起作用,因爲輸入需要一個字符串,所以你必須將其轉換。

0

1)可以使用range()與for循環中,例如:

for i in range(0, 12): 
    print(i) 

2)可以使用一系列ifelif語句爲多個可能的值,例如:

if a == 0: 
    print("something") 

elif a == 1: 
    print("something else") 

elif a == 2: 
    print("another something") 

這些做的是,首先它檢查第一個語句是否爲True,如果它不是True,它將轉到下一個語句,直到沒有語句或者其中一個語句爲True。 希望這有助於。

0

試試這個:

def get_monthly_rainfall_figures(): 
    rainfall_figures = [] 
    print("Please enter the 12 monthly rainfall figures") 
    for month in range(12): 
     in_ = int(input("Enter a value (0-300): ")) 
     if 0 <= in_ <= 300: 
      rainfall_figures.append(in_) 
     else: 
      # handle invalid input 
    return rainfall_figures 

def menu(): 
    print (""" 
0. Quit 
1. Work out and display the total 
3. Work out and display the mean 
4. Work out and display the standard deviation 
5. Work out and display the median 
6. Work out and display the lowest and second lowest 
7. Work out and display the 3 month 
8. Work out and display the months 
9. Work out display level 
""") 
    user_in = input(">>") 
    responses = {"0": quit_func, 
       "1": total_func, 
       "3": mean_func, 
       ...etc...} 
    # where quit_func, total_func, etc are functions that do the described 
    # action 
    # This design pattern is known as a hash table, and is very idiomatic 
    # in Python. In other languages you might use a switch/case block. 
    try: 
     responses[user_in]() 
    except KeyError: 
     # handle invalid input