Python 如何打破while循环?

Python 如何打破while循环?,python,python-3.x,while-loop,break,Python,Python 3.x,While Loop,Break,做作业,这是我的第一个项目,请耐心等待。虽然我已经打破了while循环,但我无法结束它。我需要一种摆脱循环的方法,而我所做的一切都不起作用。任何建议都会很有帮助的,谢谢 def main(): #Calls the main function while True: try: name = input("Please enter the student's name: ") #Asks for students name w

做作业,这是我的第一个项目,请耐心等待。虽然我已经打破了while循环,但我无法结束它。我需要一种摆脱循环的方法,而我所做的一切都不起作用。任何建议都会很有帮助的,谢谢

def main(): #Calls the main function
    while True:
        try:
            name = input("Please enter the student's name: ") #Asks for students name
            while name == "":
                print("This is invalid, please try again")
                name = input("Please enter the students name: ")


        teacher_name = input("Please enter the teacher's name: ") #Asks for teachers name 
        while teacher_name == "":
            print("This is invalid, please try again")
            teacher_name = input("Please enter the teacher's name: ")


        marker_name = input("Please enter the marker's name: ") #Asks for markers name
        while marker_name == "":
            print("This is invalid, please try again")
            marker_name = input("Please enter the marker's name: ")
            break



    except ValueError:
        print("This is invalid, please try again")

首先,您使用break打破了python中的while循环,正如您之前所做的那样。只有在循环中满足设置的条件时,才应中断。假设你想在一个计时的while循环中中断,如果数字达到100,你想中断,但是,你已经有了一个while循环的条件。然后将其放入while循环中

if x == 100:
    break
正如您现在所拥有的,您只需在几行代码之后无条件地中断while循环。您将只通过一次循环,然后每次都中断。它违背了while循环的目的


在这段代码中你到底想做什么?你能在你的问题中提供更多的细节吗?除了你想打断一下循环之外?也许我能帮你的不仅仅是给你这个关于打破循环的一般性答案。

我可以问一下为什么代码块被包装在try-except中吗

一些建议:

  • 删除try,除非您不应该引发任何错误
  • 删除break语句(在marker_name之后),因为循环应该在输入有效时结束
  • 确保所有输入while循环代码块的缩进都是相同的(您的格式混乱,因此我不确定您是否嵌套了while循环)

让我知道这是如何工作的

代码的问题在于缩进。当
标记名称
为空字符串时,您已告诉程序要
中断
。我假设您希望代码在三个值都正确时完成,因此以下代码应该适合您:

def main():
    while True:
        try:
            name = input("Please enter the student's name: ") #Asks for students name
            while name == "":
                print("This is invalid, please try again")
                name = input("Please enter the students name: ")


            teacher_name = input("Please enter the teacher's name: ") #Asks for teachers name 
            while teacher_name == "":
                print("This is invalid, please try again")
                teacher_name = input("Please enter the teacher's name: ")


            marker_name = input("Please enter the marker's name: ") #Asks for markers name
            while marker_name == "":
                print("This is invalid, please try again")
                marker_name = input("Please enter the marker's name: ")
            break

        except ValueError:
            print("This is invalid, please try again")


main()

我有点搞不懂你为什么要用try-and-except?它的用途是什么?

更多信息会有所帮助,您有多个while循环?你想和哪一个分手。我想在问了马克的名字后分手。谢谢所以你想打破这两个while循环?你可以使用
return
是的,我试着用return代替break,但它仍然没有跳出while循环。不用担心,如果这解决了你的问题,请单击我答案上的勾号。我确实做到了:)