【问题标题】:How to break between loop by creating a condition in python如何通过在python中创建条件来打破循环
【发布时间】:2021-05-20 09:27:41
【问题描述】:
lst = []
while True:
    try:
        arr = int(input("Enter number of elements: "))
        if arr == "Quit":
            break
    except ValueError:
        print("Invalid Input")
        continue
    else:
        break
while True:
    try:
        for i in range(0, arr):
            ele = int(input("Enter the elements:"))
            lst.append(ele)
            print(lst)
    except ValueError:
        print("Invalid Input")
        continue
    else:
        break

如何通过专门输入条件项来创建条件以在循环中的任何点退出程序? 就像当它要求我输入一个元素时一样,但我想在那个时候通过输入来破坏程序 “放弃”。 如何在这段代码中做到这一点? (学习者)

【问题讨论】:

  • 这能回答你的问题吗? how to stop a for loop
  • @MykolaZotko 他们说退出程序。
  • 您的问题/代码/目标不清楚。如果您只是想退出程序,请按照this post 中的说明进行操作。

标签: python if-statement while-loop break


【解决方案1】:

使用sys.exit() 退出程序完全。使用break 退出您所在的特定循环(您已经使用过)。

其他说明:

  1. 您正在执行arr = int(input(...)),但您想接受"Quit" 的输入,这是一个字符串。因此,如果用户输入“退出”,它会引发ValueError 并且循环继续。所以首先检查“退出”,如果它没有退出,然后使用 try-block 转换为int

    • 同样适用于向用户询问列表中元素的第二个循环
  2. 顺便说一句,您的第二个循环的 while True 循环应该在获取每个元素的 for 循环内。

lst = []
while True:
    arr = input("Enter number of elements: ")
    if arr == "Quit":
        sys.exit()  # will exit completely
    try:
        arr = int(arr)  # check for int in the try-block, error raised here, if not int
        break           # can put break here instead of in else, any is okay
    except ValueError:
        print("Invalid Input")
        # continue not needed here, since it loops infinitely by default


for i in range(0, arr):
    while True:
        ele = input("Enter the elements:")
        if ele == "Quit":
            sys.exit()  # will exit completely
        try:
            ele = int(ele)  # check for int in the try-block, error raised here, if not int
            lst.append(ele)
            break           # breaks out of `while` loop, not `for` loop; good
        except ValueError:
            print("Invalid Input")
            # continue not needed here, since it loops infinitely by default

print(lst)  # print the full list after all the inputs

重复输入的模式:

  • 要求用户输入
  • 如果输入是“退出”,则完全退出
  • 否则,将输入转换为 int

所以这可以放入一个函数中,你可以在两个地方调用它:

def int_or_quit(msg):
    """`msg` is the message you want to show at input"""
    while True:
        item = input(msg)
        if item == "Quit":
            sys.quit()  # will exit completely
        try:
            return int(item)  # try converting to int and return
        except ValueError:
            print("Invalid Input")
            # repeats by default

# use the function above in your two code blocks, which are now simplified:
lst = []
arr = int_or_quit("Enter number of elements: ")
# program exits before if user "Quit", next part won't execute

for i in range(0, arr):
    ele = int_or_quit("Enter an element:")
    lst.append(ele)

print(lst)

【讨论】:

    【解决方案2】:

    我可以看到您的代码 sn-p 中有 2 个块。我建议将它们组织成不同的函数,其中函数名称推断函数目标(而不是 cmets):

    def get_list_size():...
    def fill_list():...
    

    接下来要做的是决定函数的返回值:

    from typing import List, Optional
    
    def get_list_size() -> Optional[int]:
    """
    :returns: number of desired elements of list or None, if "Quit" was pressed
    :raises: ValueError exception, if non integer value was pressed
    """
    
    def fill_list(lst_size: int) -> List[int]:
    """
    returns: filled list
    throws: ValueError exception, if non integer value was pressed
    """
    

    在这里你可以看到,如何使用 Optional 类型提示将条件逻辑添加到程序中。
    Lats 要做的就是用轻量级代码填充你的函数:

    def get_list_size() -> Optional[int]:
        """
        :returns: number of desired elements of list or None, if "Quit" was pressed
        :raises: ValueError exception, if non integer value was pressed
        """
        while True:
            try:
                input_value = input("Enter number of elements: ")
    
                # Pay attention: you have to check string input_value, not    int(input_value).
                # Checking int(input_value) would raise exception before 'Quit' validation.
                if input_value == "Quit":
                    return None
    
                return int(input_value)
    
                # Could be rewritten as trinary if
                # return None if input_value == "Quit" else int(input_value)
            except ValueError:
                print("Invalid Input")
                # continue <- Not needed here
    
    
    def fill_list(lst_size: int) -> List[int]:
        """
        returns: filled list
        throws: ValueError exception, if non integer value was pressed
        """
        lst = []
        while len(lst) < lst_size:
            try:
                ele = int(input("Enter the elements:"))
                lst.append(ele)
                print(lst)
            except ValueError:
                print("Invalid Input")
            
        return lst
    

    注意:在 fill_list 函数中,你必须尝试/排除每个元素,所以 while 循环被移到了外面。
    最后要做的是运行这些函数:

    desired_list = []
    desired_list_size = get_list_size()
    if desired_list_size is not None:
        desired_list = fill_list(desired_list_size)
    

    【讨论】:

      【解决方案3】:
      def one():
          message = ""
          while message != "Quit":
              message = input("Type in Order > ")
              if message == "Run":
                  print("Run some Code")
                  message = input("What do u want to run ? > ")
                  if message == "Exel":
                      print("Runing Exel")
                  else:
                      pass
               else:
                   pass
      
      while True:
          one()
      

      在这里,您可以传入在您通过名称调用它时将运行的函数。如果你写退出它将重新开始。如果你写错了,它会重新开始。如果你愿意,你可以为此做一个 FailExeption。

      【讨论】:

        猜你喜欢
        • 2021-06-05
        • 2017-06-04
        • 1970-01-01
        • 2020-10-16
        • 1970-01-01
        • 2013-08-22
        • 2021-03-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多