AttributeError:“int”对象没有“isdigit”属性

2024-04-25 19:31:43 发布

您现在位置: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: ")

我得到以下错误。

AttributeError: 'int' object has no attribute 'isdigit'

因为我是编程新手,我真的不知道它想告诉我什么。我正在使用if cpi.isdigit():检查用户输入的是不是一个有效数字。


Tags: theforinputifconsumerevaljulyprices
3条回答

如文档所述,hereisdigit()是一个字符串方法。不能为整数调用此方法。

这条线

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' ...
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))

使用这个:

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

isdigit()仅适用于字符串。

相关问题 更多 >