【问题标题】:Error handling that prompt the user to enter only integer greater than 1提示用户仅输入大于 1 的整数的错误处理
【发布时间】:2019-02-25 14:25:56
【问题描述】:

我正在尝试编写一个 Python 函数,该函数要求输入大于 1 的整数并返回或打印输入值。

例如在代码运行时:
错误情况1:
输入大于 1 的整数:1
输出:请输入一个大于 1 的数字:

错误情况 2:
输入一个大于 1 的整数:abc345
输出:请仅输入整数值:

如果只是处理错误情况1,那很简单,我们可以使用while循环。但是还要包括非整数输入的情况,我的代码总是崩溃。

这是我的功能:

    def mult_digits():
        x = input("Enter an integer greater than 1: ")    
        while type(x) is not int:
            try:
                while int(x) <= 1:
                    x = input("Please enter a number greater than 1: ")
                    x = int(x)
            except ValueError:
                  x = input("Please enter integer values only: ")
                  x = int(x)       
        print(f"Yes, you have entered {x}.")

我的代码的问题是 int("a") 将导致 int() 的文字无效,并带有 base 10 错误。由于 input() 函数总是返回一个字符串,我们需要检查字符串是否可以转换为整数,所以我们需要 int() 函数,但这正是问题所在。

我尝试了许多不同的代码变体,包括使用 for 循环扫描输入值以查找任何非整数字符,但效率不高而且仍然崩溃。我还尝试了一个 while 循环,最终创建了一个无限循环。

有人可以帮忙吗?有没有更好的方法来编写这个函数?非常感谢,谢谢!

【问题讨论】:

    标签: python python-3.x function error-handling integer


    【解决方案1】:

    我认为你把事情弄得太复杂了。基本上,如果有人输入一个值,你首先将它传递给int(..) 函数,如果没有出错,你检查它是否大于一,所以我们可以编写一个while 循环,不断迭代直到值有效,比如:

    def mult_digits():
        msg = "Enter an integer greater than 1: "
        valid = False
        while not valid:
            x = input(msg)  
            try:
                x = int(x)
            except ValueError:
                msg = "Please enter integer values only: "
            else:
                valid = x > 1
                if not valid:
                    msg = "Enter an integer greater than 1: "
        print(f"Yes, you have entered {x}.")

    所以我们只需执行检查 in while 循环(理想情况下,您也可以将其封装在一个方法中),如果 int(..) 引发 Value 错误,则内容仍然无效,我们甚至可以更改msg。如果转换本身没有引发任何错误,我们可以检查约束,并再次给出有用的消息。

    我们一直这样做,直到 valid 设置为 True,然后我们打印该值。

    【讨论】:

    • 非常感谢您的帮助,也感谢您的详细解释!
    【解决方案2】:
    def mult_digits():
        x = input("Enter an integer greater than 1: ")
        while True:
            try:
                while int(x) <= 1:
                    x = input("Please enter a number greater than 1: ")
                    x = int(x)
                if x > 1:
                        break
            except ValueError:
                x = input("Please enter integer values only: ")
    
        print(f"Yes, you have entered {x}.")
    

    试试这个

    【讨论】:

      【解决方案3】:

      所以我在工作时看到了这个,当时它被发布到代码审查中。我想回答我,但不得不等到我回家。我将您的块分成两个块,一个用于获取输入(我讨厌冗余代码),另一个用于执行检查并要求输入。我还为数字和非数字添加了明确的错误消息。我在这里发布完整的代码:

      # -*-coding: utf-8-*-
      # !/usr/bin/python3.6
      
      import sys
      
      
      def multi_digits():
          digit = get_input()
          x = True
      
          while x:
              if digit in '23456789':
                  print(f'Yes,you have entered {digit}.')
                  x = False
              # In elif it looks like int(digit) may throw an error if it isn't a digit but
              # because of the way if statements work this wont happen. The if statement excutes
              # digit.isdigit() first, if it returns false it doesn't care about the second condition so
              # int(digit) only is checked after we confirm digit is actually a digit.
              elif digit.isdigit() and int(digit) <= 1:
                  print('Invalid input: Digit was not greater than 1')
                  digit = get_input()
              else:
                  print('Invalid input: no letters allowed')
                  digit = get_input()
      
      
      def get_input() -> str:
          return input('Enter an integer greater than 1: ')
      
      
      def main():
          multi_digits()
      
      
      if __name__ == '__main__':
          main()
      

      【讨论】:

      • 非常感谢详细的回答,一个有趣的方法。
      猜你喜欢
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多