繁体   English   中英

我的程序没有给出正确的输出?

[英]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)

该程序只是说“无”。 我希望它给我绝对值-2或说“不”是不是整数或浮点数。

更好的方法

def distance_from_zero(dist):
    a = 'Nope'
    if isinstance(dist, int) or isinstance(dist, float):
        a = abs(dist)
    return a

添加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 

演示版

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM