【问题标题】:Break is outside the loop python中断在循环python之外
【发布时间】:2012-07-30 22:12:29
【问题描述】:
while True:
    x = raw_input()
    if x =="personal information": 
         print' Edward , Height: 5,10 , EYES: brown , STATE: IL TOWN:  , SS:'
    elif x =="journal":
         name_of_file = raw_input("What is the name of the file: ")
         completeName = "C:\\python\\" + name_of_file + ".txt"
         file1 = open(completeName , "w")
         toFile = raw_input("Write what you want into the field")
         file1.write(toFile)
         file1.close()
else:
 break 

脚本不断给我一个错误,说 break 在循环之外是缩进错误吗?

【问题讨论】:

  • 你必须修复你的缩进
  • 另外,你可能会后悔没有把 open(completeName, 'w') 放在 try/catch OSError...特别是如果'completeName'是根据用户输入计算的...(只是说'):)

标签: python loops if-statement break


【解决方案1】:

是的,看看你的帖子。您的else 可能与if 语句的缩进级别一致。

while 语句的else 语句做了完全不同的事情。

【讨论】:

    【解决方案2】:

    不,这不是识别错误。您通常会“跳出”循环。 while 语句中的 else 部分不是循环结构。如果你这样做,你会发现同样的错误

    In [12]: if True:
       ....:    break
    
    SyntaxError: 'break' outside loop
    

    【讨论】:

    • 是缩进问题; OP 显然不打算使用 while: else: 构造,大多数 Python 程序员甚至从未听说过,并且在这里没有用处。
    猜你喜欢
    • 2011-01-28
    • 2015-03-07
    • 2018-01-24
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 2017-09-30
    相关资源
    最近更新 更多