如何编写具有三个参数的方法?

2024-04-20 00:48:53 发布

您现在位置:Python中文网/ 问答频道 /正文

此函数将接收三个参数。前两个是数字,第三个是布尔值。
如果正好有一个数字小于零,则函数返回True。除非布尔参数为真。在这种情况下,只有当两个数字都小于零时才会返回True。
如果不返回True,则返回False。你知道吗

def pos_neg(a,b,negative):
    if a<0 or b<0 and negative=="false":
       return True
    else:
       return False

Tags: orand函数posfalsetrue参数return
2条回答

the third is a boolean value

"false"是一个字符串。False是一个布尔值

Unless the boolean parameter is True

那么,你为什么要查假的?你知道吗

不管怎样,你可以使用布尔逻辑来使用布尔逻辑。你知道吗

试试这个

def pos_neg(a,b,negative):
    a_neg = a < 0
    b_neg = b < 0
    if negative: 
        return a_neg and b_neg  # return True if both numbers are less than zero, otherwise False
    else:
        return a_neg ^ b_neg  # returns True if *exactly* one of the numbers is less than zero, otherwise False

如果正好有一个数字小于零,则返回True,除非布尔参数为True。
在这种情况下,[负==真]只有当两个数字都小于零时才返回真。
如果不返回True,则返回False。你知道吗

def pos_neg(a, b, negative):
    if not negative:
        if (a < 0) ^ (b < 0):
            return True
        else:
            return False

    else:
        if a < 0 and b < 0:
            return True
        else:
            return False

print(pos_neg(-1, 1, False))  # True
print(pos_neg(-1, -1, False))  # False
print(pos_neg(-1, 1, True))  # False
print(pos_neg(-1, -1, True))  # True

将打印:

True
False
False
True

相关问题 更多 >