【问题标题】:Breaking out of Try Except inside While loop在 While 循环中跳出 Try except
【发布时间】:2021-12-13 23:13:20
【问题描述】:
def marks():
    while True:
        try:
            x = int(input("Enter the marks 1 : "))
            y = int(input("Enter the marks 2 : "))
            z = int(input("Enter the marks 3 : "))
        except ValueError:
            print("Please enter a integer")
        break

我是 Python 的初学者,在从输入中获得所有正确值后,我似乎无法跳出循环。为什么会这样?

【问题讨论】:

  • 把break放在try:的末尾
  • 这能回答你的问题吗? try block inside while statement
  • 我已经执行了你的程序,它正在停止循环。但是停止循环与输入有效或无效输入无关,这是我个人发现的错误

标签: python


【解决方案1】:

您的代码中存在缩进错误。 while 语句应该正确缩进。要中断循环,请将 break 语句从当前位置更改为 try 部分。代码将按如下方式工作:

  1. 尝试正常执行“try section”
  2. 一旦出错,它将跳转到 except 部分,while 循环仍将继续,它会再次要求 3 个输入
  3. 如果没有错误,它将简单地执行 try 部分并中断循环

您的代码:

def marks():
    while True:
        try:
            x = int(input("Enter the marks 1 : "))
            y = int(input("Enter the marks 2 : "))
            z = int(input("Enter the marks 3 : "))
            break         #break if all inputs are correct
        except ValueError:       #execute the moment we get error
            print("Please enter a integer")
marks()      #calling function

【讨论】:

    【解决方案2】:

    目前,在 while 循环的 1 次迭代之后,由于放置了 break 语句,您会脱离它。要解决此问题,请在所有输入均已获取且不会引发任何错误后添加 break 语句:

    while True:
        try:
            x = int(input("Enter the marks 1 : "))
            y = int(input("Enter the marks 2 : "))
            z = int(input("Enter the marks 3 : "))
            break
        except ValueError:
            print("Please enter a integer")
        
    

    【讨论】:

    • 另外,我喜欢try/except/else: break,但我是一个纯粹主义者,在try 子句中保留最少的代码。
    【解决方案3】:

    代替while True,您可以使用条件来评估您是否已收到有效输入

    def marks():
        valid = False
        while not valid:
            try:
                x = int(input("Enter the marks 1 : "))
                y = int(input("Enter the marks 2 : "))
                z = int(input("Enter the marks 3 : "))
                valid = True
            except ValueError:
                print("Please enter a integer")
    

    因此,每次您进入异常块时,您都会收到无效输入,但如果您将其设置为 value = True,则意味着您的 while 循环条件将得到满足,循环将不会继续。

    【讨论】:

    • 为什么使用这个而不是 while 循环?
    • 你是什么意思“而不是”它一个while循环?
    • 有些人可能更喜欢这个明确的,但这完全等同于在try的末尾有一个break
    • @Xnero Cory 的更正也可以被视为 OP 所犯的“基本”错误。获得经验的一部分是学习如何以最有意义的方式解决问题。 Cory 不仅提供了一个有效的解决方案,而且作为奖励,为 OP 提供了有用的提示,以在制作循环时争取人类可读的终止条件。
    • @Justin Dehorty 好吧,我个人认为应该是“while 循环条件不满足”,读“while 循环条件满足并且循环不会继续”似乎很奇怪。但你在这里似乎是对的,干杯??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多