Why Does This Work With Numbers, But Not Strings?


#1

19. Review: Built-In Functions

Hello,
I have the following code:

def distance_from_zero(distance):
	if type(distance) == int or type(distance) == float:
		return abs(distance)
	else:
		return "Nope"
  
print distance_from_zero(2)
print distance_from_zero(abc)

The output:

2
Traceback (most recent call last):
  File "python", line 8, in <module>
NameError: name 'abc' is not defined

why it works for the numbers, but it blows up with strings? shouldn’t it check the type and just print “Nope” ?


FAQ: Learn Python: Functions - Review: Built-In Functions
#2

abc is not a string, its a variable. If you make it a string, then the function should return nope


#3

Thanks, I noticed earlier that it works with single quotes, but from mysterious reason I wanted it to work my way. :confused: All is clear now, I changed the code to:

def distance_from_zero(distance):
	if (type(distance) == int or type(distance) == float):
		return abs(distance)
	else:
		return "Nope"

abc="agtew4r"
value=123
print distance_from_zero(value)
print distance_from_zero(abc)

and it works as expected.


#4