简体   繁体   中英

I want to know why this function return True and False not 1 and 0 (python 3)

When i input True, or False in function 'my_abs()' I want the result to print 1 or 0 but this function returns True and False .

def my_abs (a):
    if isinstance(a,int) or isinstance(a,float):
        if a>=0:
            b=a     
        else:
            b=-a
    elif isinstance(a, bool):
        if a == True:
            b="1"
        else:
            b="0"
    elif isinstance(a, complex):
        r=a.real
        i=a.imag
        b=((r**2)+(i**2))**(0.5)
    else:
        b="only a number can be handled!"
    return b


print(my_abs(True))
print(my_abs(False))

Since isinstance(True, int) is True, you will enter the first part of your if-test when you pass a bool as an argument. To get your desired result, try changing the order of how you test for types:

def my_abs(a):
    if isinstance(a, bool):
        if a == True:
            b = "1"
        else:
            b = "0"
    elif isinstance(a, int) or isinstance(a, float):
        if a >= 0:
            b = a
        else:
            b = -a
    elif isinstance(a, complex):
        r = a.real
        i = a.imag
        b = ((r ** 2) + (i ** 2)) ** (0.5)
    else:
        b = "only a number can be handled!"
    return b

print(my_abs(True))
print(my_abs(False))

Booleans in Python are implemented as a subclass of integers so that's why your first block of code (which is an integer) is executing.

So to fix it you have to rearrange your code to handle this behavior.

def my_abs(a):
    if isinstance(a, bool):
        if a:
            b = "1"
        else:
            b = "0"
    elif isinstance(a, int) or isinstance(a, float):
        if a >= 0:
            b = a
        else:
            b = -a
    elif isinstance(a, complex):
        r = a.real
        i = a.imag
        b = ((r ** 2) + (i ** 2)) ** (0.5)
    else:
        b = "only a number can be handled!"
    return b


print(my_abs(True))
print(my_abs(False))

Thanks:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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