繁体   English   中英

在 While 循环中跳出 Try except

[英]Breaking out of Try Except inside While loop

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 的初学者,在从输入中获得所有正确值后,我似乎无法跳出循环。 为什么会这样?

目前,在您的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")
    

您可以使用条件来评估您是否已收到有效输入,而不是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语句应该正确缩进。 要中断循环,请将 break 语句从当前位置更改为 try 部分。 该代码将按如下方式工作:

  1. 尝试正常执行“尝试部分”
  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

您缺少返回命令。 我不知道为什么 photon 会期望这个,但如果你像这样改变它,它会在一个循环后停止。

  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 : "))
        return None
      except ValueError:
        print("Please enter a integer")```

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM