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

Kri*_*Ard 8 python

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: ")
Run Code Online (Sandbox Code Playgroud)

我收到以下错误.

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

由于我是编程新手,我真的不知道它想告诉我什么.我正在使用它if cpi.isdigit():来检查用户输入的内容是否是有效数字.

mar*_*dze 6

正如这里 记录的那样isdigit()是一个字符串方法。您不能为整数调用此方法。

这条线,

cpi = eval(input("Enter the CPI for July 2015: ")) 
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)

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

>>> x = input("something: ")
something: 54
>>> type(x)
<class 'str'>
>>> x.isdigit()
True
Run Code Online (Sandbox Code Playgroud)

一切都会好起来的。

顺便说一下,在没有 sanitizin 用户输入的情况下使用 eval 可能会导致问题

考虑这个。

>>> x = eval(input("something: "))
something: __import__('os').listdir()
>>> x
['az.php', 'so', 'form.php', '.htaccess', 'action.php' ...
Run Code Online (Sandbox Code Playgroud)


usr*_*_11 6

用这个:

if(str(yourvariable).isdigit()) :
    print "number"
Run Code Online (Sandbox Code Playgroud)

isdigit() 仅适用于字符串。


Ben*_*Ben 4

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))
Run Code Online (Sandbox Code Playgroud)