【问题标题】:I need python to to check if variable is an integer using the input() command [duplicate]我需要python使用input()命令检查变量是否为整数[重复]
【发布时间】:2021-10-18 21:23:05
【问题描述】:

我需要python检查一个变量是否为整数,然后采取相应的行动。

下面是相关代码:

def data_grab():
    global fl_count #forklift count
    print("How many Heavy-lift forklifts can you replace?\n\n"
          "Please note: Only forklifts that have greater than 8,000 lbs. of lift capacity will qualify for this incentive.\n"
          "**Forklifts do  NOT need to be located at a port or airport to be eligible.**")
    forklift_count = input("Enter in # of forklifts:")
    if type(forklift_count) is int:
        fl_count = forklift_count
    else: 
        print("Invalid number. Please try again.")    
        data_grab()                       

目前,当用户实际输入整数时,会自动跳转到ELSE,而不是执行IF下的代码。

有什么想法吗?

【问题讨论】:

  • 库参考是检查您正在使用的函数的好地方。你可以从input docs 看到它总是返回一个字符串。你的类型检查总是会失败。

标签: python if-statement input integer


【解决方案1】:

试试str.isdigit() 方法:

forklift_count = input("Enter in # of forklifts:")
if forklift_count.isdigit():
    # Use int(forklift_count) to convert type to integer as pointed out by @MattDMo
    fl_count = forklift_count  
else: 
    print("Invalid number. Please try again.")  

来自文档:

str.isdigit()

如果字符串中的所有字符都是数字并且至少有一个字符,则返回 True,否则返回 False。

【讨论】:

  • 你可能想要这个:fl_count = int(forklift_count)
【解决方案2】:

这是因为无论输入什么,输入都会返回一个字符串。如果您输入数字,它会以字符串形式返回“123”,而不是以 int 形式返回 123。您可以尝试一下,除非您尝试将字符串强制转换为 int 以查看它是否为 int,或者您可以使用 if-else 并检查字符串中是否有任何非数字字符。

这是一个 try/except 示例:

in = input("Enter a number :")
try:
  in = int(in) #cast string to int
  print("Yay it is an int")
except ValueError:
  #not a number logic here
  print("that is not an int")

【讨论】:

    【解决方案3】:

    这里是初学者/可能不完整的答案,但您可以用 int() 包装 input()。

    forklift_count = int(input("Enter in # of forklifts:"))
    

    input() 返回一个字符串,所以即使你输入一个 int,它也会被视为字符串,除非你转换它。

    【讨论】:

    • 话虽如此,如果他们输入类似 3.5 的内容,它可能无法按预期工作。也许你可以使用浮点数,然后尝试获取数字的下限,如果由于非数字而引发异常,可以执行其他操作吗?
    猜你喜欢
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 2013-10-14
    • 2011-01-12
    相关资源
    最近更新 更多