初學 Python 寫互動式安裝菜單,最容易踩到的不是邏輯,而是拼字與縮排。以下這位使用者的程式在執行時直接停在第 29 行:
File "kkk.py", line 29 if choice == 0: ^ SyntaxError: invalid syntax
程式中反覆出現的是 while Ture:。Python 的常值是 True,拼成 Ture 會被當成未定義的名稱;更關鍵的是,Python 並沒有 do-while 之類的語法,而錯誤拼字會讓直譯器在後續解析時失去對應的結構,於是錯誤往往爆發在下一個看起來完全正常的 if 上——這正是第 29 行報錯的原因。把全部 Ture 改為 True,並確認大小寫一致,第一個難關就過了。
原程式的結構大致如下:
while True:
choice = int(raw_input("please input a number: "))
if choice == 0:
pass
elif choice == 1:
os.system('vi a.py')
elif choice == 2:
while True:
...
if choice == 0:
break
if choice == 1: # ← 這裡 begin 的區塊縮排與 while 同層
...
else:
continue
內層選單裡連續使用多個獨立 if,最後卻接一個 else,這個 else 只會黏在最後一個 if 上,於是「輸入 1 之後又輸入 1」這種情況會落進 else 而 continue,行為與預期不符。正確做法是把互斥的選項改成 if / elif / elif / else 一整串,並確認整串都縮排在 while 之內。
import os
def show(title, items):
print("=" * 30)
print(title)
for key, text in items:
print("%s %s" % (key, text))
def basic_menu():
while True:
show("Install Basic service", [("0", "Return"), ("1", "MySQL"),
("2", "PostgreSQL"), ("3", "Web Service")])
choice = int(raw_input("please input a number: "))
if choice == 0:
break # 回到上一層,而不是結束程式
elif choice == 1:
print("we will install mysql")
elif choice == 2:
print("we will install postgresql")
elif choice == 3:
print("we will install tomcat, apache, jdk....")
else:
print("Sorry, it is not a valid choice!")
def main_menu():
while True:
show("we will install V2-Program", [("0", "Exit"), ("1", "View parameter file"),
("2", "Basic service"), ("3", "Application service")])
choice = int(raw_input("please input a number: "))
if choice == 0:
break
elif choice == 1:
os.system('vi a.py')
elif choice == 2:
basic_menu()
elif choice == 3:
print("application service menu")
else:
print("Sorry, it is not a valid choice!")
main_menu()
改成函式之後有兩個好處:每層菜單的 break 只跳出自己那一層,天然實現「返回上一層」;而不斷重複的 print 也被收斂到一個 show() 裡。另外提醒兩點,raw_input 在 Python 3 已改名為 input,且使用者輸入非數字時 int() 會拋出 ValueError,正式版本建議用 try/except 包起來。