Why Does This Work With Numbers, But Not Strings?


19. Review: Built-In Functions

I have the following code:

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

The output:

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

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


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)
		return "Nope"

print distance_from_zero(value)
print distance_from_zero(abc)

and it works as expected.