2014-09-21 107 views
-1

我在Python代碼中的「Syntax Error:invalid syntax」消息中遇到問題,這些代碼一直在將目標帖子移到我身上。在python 2.7中使用if語句的語法錯誤

這裏的示例代碼:

another_answer = int(raw_input("> ") 

if another_answer == 1: 
    print "The pirate's body slowly goes limp and he whispers to you......." 
    print "Good luck my son. You might need this." 
    get_gold() 

    print: "Do you want to continue to the next room?" 

當我在shell我得到下面這條命令:

File "ex36.py", line 179 
    if another_answer == 1: 
         ^
SyntaxError: invalid syntax 

我發現這個奇怪的,除去冒號後我得到一個錯誤信息在下一行:

File "ex36.py", line 180 
print "The pirate's body slowly goes limp and he slowly whispers to you......." 
    ^
SyntaxError: invalid syntax 

我在上面找到的stackoverflow中心的類似問題間距和縮進,但我已經看過,一切似乎都很好。

+0

那麼,這裏有一個縮進錯誤; 'if'語句必須與'another_answer ='語句具有相同的縮進級別。但是還有_another_語法錯誤導致您無法看到該錯誤。 – abarnert 2014-09-21 03:08:36

回答

2

前行缺少一個右括號:

another_answer = int(raw_input("> ") 
#     ^  ^ ^^ 
#     \   \--// 
#      \-----------? 

Python允許用括號括起來的時候表達過的物理線路,所以當你關閉括號的Python繼續尋找其餘表達方式。當它到達:時,表達式就不再有意義了,並引發了一個異常。

+0

這是高興的,但是,當我打開Python的問題時,我發現Martijn Pieters。有什麼你不瞭解Python的嗎?放手! – Nabin 2014-09-21 03:14:09

+0

之前已評論過類似評論,因爲從第1天開始就是粉絲。:-) – Nabin 2014-09-21 03:14:43

+0

謝謝Martijn! – 2014-09-22 14:25:37

1

您在第一行缺少右括號。冒號只是第一個不可能成爲實際函數參數一部分的字符。

1

你有兩個問題,你必須解決這兩個問題。

第一個是你缺少一個右括號:

another_answer = int(raw_input("> ") 

這意味着Python的仍然在試圖編譯參數調用int當它到達下一行。直到結腸,一切仍是合法的,因爲你可以一直寫這個:

another_answer = int(raw_input("> ") 
        if another_answer == 1 
        else '42') 

但是,一旦你到達結腸,有可能出現在沒有有效的表達,因此,這就是你得到的SyntaxError

一般情況下,當你在一個行,其中絕對沒有錯看起來得到SyntaxError,看前行 - 通常這是一個缺少)(或]})。


但是,如果你解決了這個問題,你將會遇到另一個問題。雖然你聲稱這:

Similar questions I've found on stackoverflow center around improper spacing and indentation, but I've looked that over and everything seems to be well.

...一切絕對是得好:

another_answer = int(raw_input("> ") 

    if another_answer == 1: 

if聲明縮進到another_answer陳述的權利。這是違法的,並且會引起IndentationError。您只能在Python中更改縮進級別以進入或退出由複合語句控制的塊。


你也是你的代碼有至少一個以上的錯誤:

print: "Do you want to continue to the next room?" 

這將引發SyntaxErrorprint不是像ifdef這樣的複合語句,所以它不需要冒號。

1

很容易發現您錯過了第一行的右括號。