我的程序没有给出正确的输出?
My program is not giving the correct output?
我正在尝试让 -2 的绝对值出现在 python 上。
def distance_from_zero(a):
if type(a) == int or type(a) == float:
return abs(a)
else:
return "Nope"
distance_from_zero(-2)
程序只是说 "None"。我希望它给我 -2 的绝对值,或者说 "nope" 是数字不是整数或浮点数。
添加 print
以查看输出。
def distance_from_zero(a):
if type(a) == int or type(a) == float:
return abs(a)
else:
return "Nope"
print distance_from_zero(-2)
print distance_from_zero('hi')
输出:
➜ python ./distance.py
2
Nope
稍微好一点的方法,
def distance_from_zero(dist):
a = 'Nope'
if isinstance(dist, int) or isinstance(dist, float):
a = abs(dist)
return a
我正在尝试让 -2 的绝对值出现在 python 上。
def distance_from_zero(a):
if type(a) == int or type(a) == float:
return abs(a)
else:
return "Nope"
distance_from_zero(-2)
程序只是说 "None"。我希望它给我 -2 的绝对值,或者说 "nope" 是数字不是整数或浮点数。
添加 print
以查看输出。
def distance_from_zero(a):
if type(a) == int or type(a) == float:
return abs(a)
else:
return "Nope"
print distance_from_zero(-2)
print distance_from_zero('hi')
输出:
➜ python ./distance.py
2
Nope
稍微好一点的方法,
def distance_from_zero(dist):
a = 'Nope'
if isinstance(dist, int) or isinstance(dist, float):
a = abs(dist)
return a