【问题标题】:How to get only integer or float input如何仅获取整数或浮点输入
【发布时间】:2021-12-06 12:49:48
【问题描述】:

我正在尝试用 python 制作一个计算器。但是,我希望用户能够输入整数或浮点数。但不是字符串,怎么办?

这是我当前的代码,但是,if 语句没有完成预期的工作。

def calculator():
     x = (input("Please enter a number: "))

     y = (input("Please enter a second number"))

     if x or y != int or float:

          print("Invalid input, please enter a number")
          x = input("Please enter a number: ")
          y = input("Now, please enter a second number: Press enter to leave blank: ")

【问题讨论】:

  • 你试过type(x) is not int or type(x) is not float吗?
  • A == B or CA == B or A == C 不同 - 它是 (A == B) or (C is True)
  • @marcelh h 它不起作用,因为一开始,python 假定输入是一个字符串。
  • 有没有办法写 x = (int(float("Enter a number: "))) 来获得整数或浮点输入
  • @nutella1555 你是对的,我立即关注 if 语句,但这不是问题。您可以在下面找到建议。

标签: python string if-statement input integer


【解决方案1】:

您可以在输入之前添加 int 或 float... 例如:

x = int(input("Please enter a number: "))

所以如果你输入一个字符串,它不会接受它并导致一个 Traceback

【讨论】:

  • 谢谢.. 但我希望用户能够输入浮点数。像 float 或 int 但不是字符串。
【解决方案2】:

您输入的始终是字符串,即使有人输入了数字。要将输入转换为 int 或 float,请使用:

x = int(input("text"))
y = float(input("text"))

请注意,如果您只需要数字,则应验证输入,例如

def check_user_input(input):
    try:
        # Convert it into integer
        val = int(input)
        print("Input is an integer number. Number = ", val)
    except ValueError:
        try:
            # Convert it into float
            val = float(input)
            print("Input is a float  number. Number = ", val)
        except ValueError:
            print("No.. input is not a number. It's a string")


input1 = input("Enter your Age ")
check_user_input(input1)

input2 = input("Enter any number ")
check_user_input(input2)

input2 = input("Enter the last number ")
check_user_input(input2)

【讨论】:

    【解决方案3】:

    您可以尝试以下方法:

    
    while True:
        try:
            x = input('Enter int or float:')
    
            if x.find('.') == -1:
                x = int(x)
                break
            else:
                x = float(x)
                break
        except ValueError:
            print('Something went wrong, try again.')
    
    print(type(x))
    
    

    您有一个解析用户输入的 while 循环。 如果它包含.,则用户输入float,否则输入int,从而在各自的语句中进行解析。 如果格式不正确,则会引发 ValueError 并将其排除在外,打印出用户应该再试一次。该信息可以更新为更具暗示性。但是,如果任一转换成功,则退出 while 循环并打印类型。也可以使用 KeyboradInterrupt Ctrl + C 留下循环。

    【讨论】:

    • @marcel_h 如果 x.find(".") == -1: 怎么办? == -1 有什么作用?
    • @nutella1555 作为input 捕获的用户输入是一个字符串。使用此if 条件,您可以检查字符串是否包含.,这表明输入了floatfind 本身返回第一次出现的位置,如果没有找到字符,则返回 -1。在这种情况下,未找到表示输入了 int,因此 int 解析在 == -1 部分中。如果它仍然不是int,则会引发ValueError。如果有帮助,我会更新上面的答案。
    【解决方案4】:

    使用内置的isinstance函数。

    def calculator():
        def checker():
            try:
                x = int(input("Please enter a number: "))
                assert (isinstance(x, int) or isinstance(x, float))
                y = int(input("Please enter a second number: "))
                assert (isinstance(y, int) or isinstance(y, float))
            except (AssertionError, ValueError):
                print("Invalid input!")
                checker()
        checker()
        # <Your code here...>
    calculator()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-22
      • 2018-09-23
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多