简体   繁体   English

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

[英]My program is not giving the correct output?

I'm trying to get the absolute value of -2 to appear on python. 我正在尝试让-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)

The programs just says "None". 该程序只是说“无”。 I want it to give me the absolute value of -2 or say "nope" is the number is not an int or float. 我希望它给我绝对值-2或说“不”是不是整数或浮点数。

slightly a better way, 更好的方法

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

Add print to see the output. 添加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')

Output: 输出:

➜  python ./distance.py
2
Nope 

Demo 演示版

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

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