2016-10-21 14 views
0

我正在寫一個簡單的程序,它看起來像這樣:有沒有辦法將elif和while表達式轉換爲一個?

while True: 
    choice = float(input("options: ")) 

    if choice == 1: 
     # Do something 

    elif choice == 2: 
     # Do something 

    elif choice == 3: # <--- seems redudant 
     while choice == 3: 
      choice_return = input("do you want to return?: ") 

       if choice_return == "yes": 
        choice = None 
       else: 
        pass 

    elif choice == 4: 
     break 

正如代碼所指出的,「ELIF statment」似乎是多餘的,因爲它具有相同的條件「而循環」的。當然你也可以簡單地寫代碼如下:

while True: 
    choice = float(input("options: ")) 

    if choice == 1: 
     # Do something 

    elif choice == 2: 
     # Do something 

    elif choice == 4: 
     break 

    while choice == 3: <--- three after four, no!!! 
     choice_return = input("do you want to return?: ")  
      if choice_return == "yes": 
        choice = None 
      else: 
       pass 

不看壞在這個例子中,但在實際的代碼,它有點遺址的結構(和我的強迫症不允許這)。有沒有辦法在維持秩序的同時消除冗餘?

注意:假定「選擇號碼」是固定的。

+0

是否只有4個用戶可以輸入的選項? –

+0

你可以使用開關盒。 –

+0

Python沒有'switch'。 – bgporter

回答

1

你能堅持到if/elif結構,並通過在功能包裝的elif choice == 3邏輯和功能使用while True配方收拾東西:

def myfunc() 
    while True: 
     choice_return = input("do you want to return?: ") 
     if choice_return == "yes": 
      return None # None here is redundant 

while True: 
    choice = float(input("options: ")) 

    if choice == 1: 
     ... 

    elif choice == 3: 
     choice = myfunc() 
    ... 
0

似乎沒有任何理由來使用choice作爲while循環中的條件。對其進行重構,以便在適當時使用break來停止循環。

elif choice == 3: # <--- seems redudant 
    while True: 
     choice_return = input("do you want to return?: ") 
     if choice_return == "yes": 
      break 
0

把inner while循環放到一個函數中,代碼就會更乾淨。你仍然有兩個測試,但整數比較速度很快 - 那麼爲什麼你使用float

更好的是,如果你可以,但每個「案例」成一個函數,你可以使用函數列表。

# Functions return True to break out of the loop, otherwise False 

def case1(): 
    # Do something 

def case2(): 
    # Do something 

def case3(): 
    # Do something 

def case4(): 
    # Do something 

cases = [case1, case2, case3, case4] 

while True: 
    choice = int(input("options: ")) 

    if choice < len(cases) and choice >= 0: 
     if cases[choice](): 
      break 
    else: 
     print("Invalid option", choice) 
相關問題