Posts Tagged ‘truthvalues’

Python: Truthvalues

def distance_from_zero(a):
    if type(a) == int or float:

But, if they enter something that isn’t a number they get an error. The reason is that this if statement will always be True. This is because of a concept called TRUTHVALUES. When Python has an if statement it checks the TRUTHVALUES of the statements. Now almost all values in Python are True. The only values that are False are FalseNone0 or any equivalent number-type, and any empty container like [] () {} set() "" ''. Everything else is True.

Thus, when someone writes or float they are really writing or True. To get around this we would need to check each one individually like so –

if type(a) == int or type(a) == float:

There are other ways of doing this like if-in, but I’ll leave you guys to figure that out.


Stackoverflow Solutions

Just started! Have not answered any questions.