2014-09-28 93 views
-5

這裏是我的代碼,如下所示:Elif語句語法錯誤:語法無效?

menu= "Welcome to the menu\n"          \ 
+  "Please select an option below:\n"       \ 
+ ( "0 - Enter a number\n" + "1 - Display current number\n" + \ 
"2 - Divisibility checking\n" + "3 - Perfect checking\n"  + \ 
"4 - Triangular checking\n" + "5 - Quit\n") 
x == ("") 
while option!=5:             # <<< Q2 
    print(menu) 
    option= int(input("Enter option: ")) 
    if option==0: 
     x= int(input("What is your number?: ")) 
     while x <=0: 
      x= int(input("Must be positive, please! What is your number?: ") 
    elif option==1:            # <<< Q1 
     print("The current number is", x) 
     elif (x == ""): 
      print("No number yet - Please input a number and try again.") 
      x= int(input("What is your number?: ")) 

Q1: 我想知道爲什麼我一直得到一個錯誤消息我的代碼line 14,第二elif聲明。

Q2: 我也想知道怎麼樣,我的第一個while發言,我如果我不提示用戶輸入選項還可以定義「option」爲option!=5然後print菜單。

對這兩種情況的任何幫助都會很感激。

謝謝。

+2

你讀過這段代碼嗎?你知道'elif'屬於什麼嗎? – 2014-09-28 16:57:17

+0

在你的while循環沒有做任何事情之前,你不能象'elif(x ==「」)''也有'x ==(「」)''那樣嵌套elif語句。 – 2014-09-28 17:01:43

+1

您已忘記關閉前一行的int()括號。 – 2014-09-28 17:09:37

回答

0

關於你的第二條ELIF語句,我認爲你的嵌套錯誤。

你有一個外決策樹,你去哪裏在可用選項,樹是:

你不需要在內部ELIF,因爲它不是一個else語句所選擇的選項。您剛剛開始一個新的決策樹(您嘗試查找x是否已分配,如果不請求數字,則顯示該數字)。因此,正確的代碼應該是:

elif option == 1: 
    if x == "": 
     print("No number yet - Please input a number and try again.") 
     x= int(input("What is your number?: ")) 
    else: 
     print("The current number is", x) 
elif option == 2 
    --> Handling of option 2 

這應該有效。我把自由首先把if語句,否則你會得到輸出

"The current number is " 
"No number yet - Please input a number and try again."... 

我覺得這是一個很值得什麼意思伊格納西奧,當他問,如果你知道的elif屬於什麼。

+0

我想你錯過了最重要的問題,那就是缺少一個')'。 – SethMMorton 2014-09-29 03:34:48

+0

這確實是一個問題,Martijn正確指出了,但是當她在第二個elif語句中提到了一個問題時(因此編輯錯誤,Q1應該在代碼中進一步向下標記兩行),但我仍然認爲錯誤縮進的elif是她的問題。 – MichaelA 2014-09-29 19:14:07