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:&#39; int&#39;对象没有属性&#39; isdigit&#39;
由于我是编程新手,所以我真的不知道它要告诉我什么。我使用if cpi.isdigit():
检查用户输入的内容是否为有效数字。
答案 0 :(得分:4)
记录here CREATE TABLE dbo.PCT
(
PCT_ID INT NOT NULL
CONSTRAINT PK_PCT
PRIMARY KEY CLUSTERED
IDENTITY(1,1)
, SomeChar VARCHAR(50) NOT NULL
, SomeCharToInt AS CONVERT(INT, REPLACE(SomeChar, 'M', ''))
);
CREATE INDEX IX_PCT_SomeCharToInt
ON dbo.PCT(SomeCharToInt);
INSERT INTO dbo.PCT(SomeChar)
VALUES ('2015M08');
SELECT SomeCharToInt
FROM dbo.PCT;
是一种字符串方法。你不能为整数调用这个方法。
这一行,
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
一切都会好的。
顺便使用没有sanitizin用户输入的eval可能会导致问题
考虑一下。
>>> x = input("something: ")
something: 54
>>> type(x)
<class 'str'>
>>> x.isdigit()
True
答案 1 :(得分:3)
使用此:
if(str(yourvariable).isdigit()) :
print "number"
isdigit()
仅适用于字符串。
答案 2 :(得分:2)
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))
答案 3 :(得分:0)
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.")