Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

I'm getting the following error.

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

Since I'm new to programming, I don't really know what it's trying to tell me. I'm using the if cpi.isdigit(): to check to see if what the user entered is a valid number.

like image 782
Kristofer Ard Avatar asked Oct 10 '15 00:10

Kristofer Ard


1 Answers

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))
like image 155
Ben Avatar answered Oct 21 '22 08:10

Ben