首页 文章

AttributeError:'int' object没有属性'isdigit'

提问于
浏览
5
numOfYears = 0
cpi = eval(input("Enter the CPI for July 2015: "))
if cpi.isdigit():
    while cpi < (cpi * 2):
        cpi *= 1.025
        numOfYears += 1
    print("Consumer prices will double in " + str(numOfYears) + " years.")
while not cpi.isdigit():
    print("Bad input")
    cpi = input("Enter the CPI for July 2015: ")

我收到以下错误 .

AttributeError:'int'对象没有属性'isdigit'

因为我真的知道它是什么's trying to tell me. I'使用 if cpi.isdigit(): 来检查用户输入的是否是有效数字 .

4 回答

  • 0
    numOfYears = 0
    # since it's just suppposed to be a number, don't use eval!
    # It's a security risk
    # Simply cast it to a string
    cpi = str(input("Enter the CPI for July 2015: "))
    
    # keep going until you know it's a digit
    while not cpi.isdigit():
        print("Bad input")
        cpi = input("Enter the CPI for July 2015: ")
    
    # now that you know it's a digit, make it a float
    cpi = float(cpi)
    while cpi < (cpi * 2):
        cpi *= 1.025
        numOfYears += 1
    # it's also easier to format the string
    print("Consumer prices will double in {} years.".format(numOfYears))
    
  • 2

    据记载here isdigit() 是一个字符串方法 . 您不能为整数调用此方法 .

    这条线,

    cpi = eval(input("Enter the CPI for July 2015: "))
    

    evaluates 用户输入为整数 .

    >>> x = eval(input("something: "))
    something: 34
    >>> type(x)
    <class 'int'>
    >>> x.isdigit()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'int' object has no attribute 'isdigit'
    

    但是如果你删除 eval 方法(你最好这样做),

    >>> x = input("something: ")
    something: 54
    >>> type(x)
    <class 'str'>
    >>> x.isdigit()
    True
    

    一切都会好起来的 .

    顺便使用eval而不用sanitizin用户输入可能会导致问题

    考虑一下 .

    >>> x = eval(input("something: "))
    something: __import__('os').listdir()
    >>> x
    ['az.php', 'so', 'form.php', '.htaccess', 'action.php' ...
    
  • 1

    用这个:

    if(str(yourvariable).isdigit()) :
        print "number"
    

    isdigit() 仅适用于字符串 .

  • 3

    eval() is very dangerous!int() 内置函数可以将字符串转换为数字 .

    如果您想在用户未输入数字时捕获错误,请使用 try...except ,如下所示:

    numOfYears = 0
    
    while numOfYears == 0:
        try:
            cpi = int(input("Enter the CPI for July 2015: "))
        except ValueError:
            print("Bad input")
        else:
            while cpi < (cpi * 2):
                cpi *= 1.025
                numOfYears += 1
    
    print("Consumer prices will double in", numOfYears, "years.")
    

相关问题