AttributeError: object 'int' does not have attribute 'isdigit'

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: ")

I get the following error.

AttributeError: object 'int' does not have attribute 'isdigit'

Since I am new to programming, I do not know what he is trying to tell me. I use if cpi.isdigit():to check if the user-entered number is valid.

+4
source share
4 answers
numOfYears = 0
# since it just suppposed to be a number, don't use eval!
# It a security risk
# Simply cast it to a string
cpi = str(input("Enter the CPI for July 2015: "))

# keep going until you know it a digit
while not cpi.isdigit():
    print("Bad input")
    cpi = input("Enter the CPI for July 2015: ")

# now that you know it a digit, make it a float
cpi = float(cpi)
while cpi < (cpi * 2):
    cpi *= 1.025
    numOfYears += 1
# it also easier to format the string
print("Consumer prices will double in {} years.".format(numOfYears))
+1
source

As stated here isdigit() is a string method. You cannot call this method for integers.

This line,

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

evaluates user input in integer.

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

But if you delete the method eval(you better do it),

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

everything will be fine.

By the way, using eval without user sanitizin can cause problems.

consider this.

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

eval() ! int() .

If you want to catch an error if the user did not enter a number, just use try...exceptas follows:

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.")
0
source

Use this:

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

isdigit() only works for strings.

0
source

Source: https://habr.com/ru/post/1611042/


All Articles