Functions


#1

hey guys,
can u guys tell me the difference between

def distance_from_zero(num):
if type(num) == int or type(num) == float:
return abs(num)
else:
return “Nope”

AND

def distance_from_zero(num):
if type(num) == int or float:
return abs(num)
else:
return “Nope”

the second code seems to give me an error.
why cant we use the OR function without using type function the second time


#2

because then the second condition simply is:

if float:

python will simply evaluate if float is true


#3

See this.
Go to bottom of this page and check the operator precedence table

https://codescracker.com/python/python-operators.htm


#4

To explain @stetim94’s example…

>>> float
<class 'float'>
>>> 

In other words, float is an object. Objects are truthy

if __object__: 

will always be true (unless the object is empty, zero, False or None), . This short-circuits the expression,

if type(num) == int or float:

The righthand operand needs to be an expression that can potentially yield False.

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

Examples

>>> print (True if '' else False)
False
>>> print (True if 0 else False)
False
>>> print (True if None else False)
False
>>> print (True if [] else False)
False
>>> print (True if [1] else False)
True
>>> print (True if {} else False)
False
>>> print (True if {'a': 1} else False)
True
>>> print (True if float else False)
True
>>> print (True if str else False)
True
>>> 

#5

thanks a lot sir…that explained it pretty much


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.