2015-11-13 64 views
0

出於某種原因,我得到一個NameError異常升高當我嘗試執行此代碼:你將如何退出Python中的字符串文字循環?

while True: 
    fileString = input("Enter your command: ") 
    print(fileString) 
    if fileString is "end": 
     break 
    else: 
     print("\nSomething went wrong! Please try again.") 
     continue 
print("The program will now shut down.") 

我想打破循環時,在輸入輸入「結束」。

+1

你使用的是什麼版本的Python? – njzk2

+0

** tl; dr **不要使用'is'關鍵字作爲初學者。這不是你想要的機器人。使用== == – smci

+0

大家都在急着回答,3個不同的人似乎都錯過了NameError。 – user2357112

回答

3
Two things to note here. 
(1) Use raw_input(), and not input(). With integers, input() will be ok 
    But you seem to be entering string. 
    fileString = raw_input("Enter your command: ") 
(2) Change the if statement to 
    if fileString == "end": 
+0

如果這是Python 2,'input'只是錯誤的。在Python 3中,'input'與Py2的'raw_input'相同。沒有隱含的'eval'。 – ShadowRanger

+2

@ShadowRanger:它是發佈代碼中唯一可以產生NameError的地方,所以它可能是Python 2的'input'。如果不是,我們需要看到更多的OP代碼。 – user2357112

+0

我正在使用Python 3(最新版本),在IDLE中編譯。此解決方案工作。謝謝balabhi :) – moshulu

3
if fileString is "end" 

這條線是你的問題,與==(試驗值相等),而不是is(測試指針相等)比較fileString平等,以「結束」。

在一個側面說明的話,建議在線路8

+0

這不是你正在尋找的問題。再次閱讀這個問題 – njzk2

0

去除冗餘continue在Python,「是」的身份測試。要測試相等性,請將'is'替換爲'=='。那可能會起作用。

相關問題