Question

I am having a slight issue with math's .isnan() function in python. Pretty much, I have this code:

import math        
diceChoice = raw_input('Which dice will you throw?\n 4 sides\n 6 sides\n 12 sides?\n>')

if math.isnan(float(diceChoice)):
    print(str(diceChoice) + ' is an invalid choice')

and if diceChoice isn't a number (eg 'a') it gives me the error:

ValueError: could not convert string to float: a

If I don't convert it to a float, it gives me another error saying that it needs to be a float. I must be doing something wrong as the isnan function would be useless if it only accepts numbers. Can someone please help me

Thanks in advance

Was it helpful?

Solution 2

isnan() is really only used to check if a number doesn't have a finite value. Consider instead doing something like:

if not diceChoice.isdigit():

The error is raised because you attempt to convert a string to an integer with float('a'). Easier to just do the above.

OTHER TIPS

The float() function used on any other string other than a decimal number, 'nan', '-inf' or 'inf' (or slight variants of those strings) will throw a ValueError instead, because anything else is not a valid floating point value. math.isnan() only works on the special float value float('nan'), but it is not ever called if float() raises an exception first.

Use exception handling to catch that error instead:

try:
    diceChoice = int(diceChoice))
except ValueError:
    print(diceChoice, 'is an invalid choice')

I used int() instead because your input requires that the user enters a whole number.

Just to be explicit: float('nan') is a specific floating point value to signify the output of certain mathematical operations that are not an exception. It is never used to signify invalid input.

NaN are used to define things that are not numbers in a floating point context like 0/0 or the square root of a negative number for example. You can use isdigit or something else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top