你将如何退出带有 Python 中的字符串文字的循环?

How would you exit a loop with a string literal in Python?

出于某种原因,当我尝试执行此代码时出现 NameError 异常:

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.")

我想在输入中输入 "end" 时打破循环。

if fileString is "end"

那一行是你的问题,将 fileString 与 "end" 的相等性与 ==(值相等性测试)而不是 is(指针相等性测试)进行比较。

附带说明一下,我建议删除第 8 行多余的 continue

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":

在 Python 中,'is' 测试身份。要测试相等性,请将 'is' 替换为“==”。到时候可能有用。