【问题标题】:Where do i put the break in my code?我在哪里把中断放在我的代码中?
【发布时间】:2023-09-18 16:43:02
【问题描述】:
print'Personal information, journal and more to come'

while True:

    x = raw_input()
    if x =="personal information": 
         print' Edward , Height: 5,10 , EYES: brown , STATE: IL TOWN:  , SS:'
    elif x =="journal":
       print'would you like  you open a journal or create a new one? open or create'
if x =='createfile':
           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()
elif x =='openfile':
       print'what file would you like to open' 
       y = raw_input()
       read = open(y , 'r')
       name = read.readline()
       print (name)
       break

每次我尝试运行程序时,它都会告诉我 break 已超出循环,但我不知道我还能在哪里设置 break。还有什么是记住在循环末尾放置中断的好方法?

【问题讨论】:

  • 爱德华,我看过你之前的一些问题,我想问一下。您是否学习过任何基本的 Python 教程?缩进似乎很麻烦,这是python中一个非常的基本概念。
  • 这不是一个坏问题。这是一个关于非常基本的误解的基本问题,但它并不不清楚或不恰当,那么为什么它被否决了?
  • 我已经完成了一个基本的 Python 课程,但是我仍然在缩进方面遇到了很多麻烦,也许这个教程很糟糕,你有一个关于缩进的好教程吗?
  • @JasonFruit:试试看这里的风格指南:python.org/dev/peps/pep-0008。我建议使用 IDE 或类似 vim 的工具,这样您就可以设置自动缩进。
  • 我建议你从非常简单的脚本开始,缩进一些东西......看看当你改变缩进时情况如何:)

标签: python loops break


【解决方案1】:

坦率地说:你的break 在循环之外。您有一个不在 while 循环内的 if 语句。

if x =='createfile':的缩进方式,在while循环运行后运行。

我猜你想重新缩进你的代码,以便它们都包含在循环中。我还将if 更改为elif,因为这里看起来更合适:

print 'Personal information, journal and more to come'

while True:

    x = raw_input()
    if x =="personal information": 
         print' Edward , Height: 5,10 , EYES: brown , STATE: IL TOWN:  , SS:'
    elif x =="journal":
         print'would you like  you open a journal or create a new one? open or create'
    elif x =='createfile':
         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()
    elif x =='openfile':
         print'what file would you like to open' 
         y = raw_input()
         read = open(y , 'r')
         name = read.readline()
         print (name)
         break

【讨论】:

    【解决方案2】:

    您的 break 语句是循环之外的 ifelif 语句的一部分。 Python 对空格敏感。您应该将所有 ifelif 语句缩进到循环内。

    【讨论】:

      【解决方案3】:

      你的缩进是错误的。似乎您正试图摆脱 while 循环,但您的 while 循环在

      处结束
      if x == 'createfile'
      

      声明。

      您必须修复 if 和 elif 语句的缩进,以便它们在 while 循环内,然后您的 break 语句才能工作。

      【讨论】:

        最近更新 更多