Ced Wayne Ced Wayne - 7 months ago 5
Python Question

Python 3 - Code will not recognize a user input larger than 1 as numeric

I created the following python code for an exercise in Python for informatics. The code will run, but will not recognize an input form the user that is larger than 1 as numeric. Any assistance would be appreciated.

def isfloat(string):
try:
float(string)
if float(string) == True:
return True
except ValueError:
return False

user_input = input('Please enter a real number. Type \"done\" to exit and tally your entries \n> ')
data = 0
count = 0

while isfloat(user_input) == True:
data = data + float(user_input)
count = count + 1
user_input = input("Please enter another value \n> ")
isfloat(user_input)

else:
if (isfloat(user_input) == False) and (user_input == "done"):
print("The sum of your entries is: " + str(data))
print("The number of entries was: " + str(count))
exit()
else:
print("The entry was not a numeric value \n")
print("The sum of your valid entries is: " + str(data))
print("The number of valid entries was: " + str(count))
exit()

Answer

The problem lies in the fact that float(string) will never return True; it will always return a number of type float or it will raise a ValueError if the input cannot be converted to a float.

To fix this, you'll need to remove your if statement, and simply return True after calling float(string) in your isfloat function. If float(string) raises a ValueError, isfloat returns False as you would expect; otherwise, it will proceed and return True.

def isfloat(string):
    try:
        float(string)
        return True
    except ValueError:
        return False
Comments