我正在寫一個簡單的程序,它看起來像這樣:有沒有辦法將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
不看壞在這個例子中,但在實際的代碼,它有點遺址的結構(和我的強迫症不允許這)。有沒有辦法在維持秩序的同時消除冗餘?
注意:假定「選擇號碼」是固定的。
是否只有4個用戶可以輸入的選項? –
你可以使用開關盒。 –
Python沒有'switch'。 – bgporter