【问题标题】:Why does my python 2.7 code print 'false' when the components are true?当组件为真时,为什么我的 python 2.7 代码会打印“假”?
【发布时间】:2021-12-05 23:29:21
【问题描述】:

我正在处理两个用户定义的函数,一个调用第一个函数,它确定给定的输入是平行四边形还是矩形,但是当我设置我的 if 语句时,即使输入满足“真”类别后一个函数,它仍然打印为“False”(即使我用下面的东西替换“False”打印,比如打印“No”)我认为这是我在后一个语句中调用前一个函数的方式。

#the function, isPara below works perfect
def isPara(s1, s2):
    '''if base lengths are same, it will return true'''
    if b1 == b2:
        isPara = True
        print 'True'
    else:
        isPara = False
        print 'False'

#however when I call isPara into isRec, the output displays as false even if it's true or doesn't #print false

def isRec(s1, s2, angle):
    '''if isPara is true '''
    if isPara is True:
        if angle == 90:
            isRec = True
            print 'True'
    else:
        isRec = False
        print 'Not true'

s1 =3 
s2 = 3
angle = 90

isPara (s1, s2)
isRec( s1, s2, angle)

【问题讨论】:

  • isPara 是一个函数对象,不会和True 是同一个对象。您可能打算调用该函数,例如if isPara(s1, s2): 你也没有从isPara 返回任何东西,所以isPara 将总是返回None。你想写return True,而不是isPara = True
  • 用您自己的话说,您认为if isPara is True 的作用究竟是什么?为什么?用您自己的话来说,您如何调用函数?你想在那个时候调用一个函数吗?你的代码这样做吗? (提示:之前你写isPara (s1, s2)时,那是调用函数吗?)

标签: python function python-2.7 boolean


【解决方案1】:

isPara() 是一个有 2 个参数的函数,因此您需要从 isRec() 相应地调用它。 您的代码中几乎没有更新,它按预期工作:

def isPara(s1, s2):
    '''if base lengths are same, it will return true'''
    isPara = False
    if s1 == s2:
        isPara = True
        print ('True')
    else:
        isPara = False
        print ('False')
    return isPara

def isRec(s1, s2, angle):
    '''if isPara is true '''
    if isPara(s1, s2):           <<< Here is the change, call function
        if angle == 90:
            isRec = True
            print ('True')
    else:
        isRec = False
        print ('Not true')

s1 =3 
s2 = 3
angle = 90

isPara (s1, s2)
isRec( s1, s2, angle)

输出:

True
True
True

【讨论】:

    【解决方案2】:

    正如 Brian 所说,您需要从函数中返回值,您还需要将 isPara 传递给函数 isRec。

    def isPara(b1, b2):
        '''if base lengths are same, it will return true'''
        return True if b1 == b2 else False
    
    def isRec(angle, isPara):
        '''if isPara is true '''
        return True if isPara is True and angle == 90 else False
    
    s1, s2, angle = 3, 3, 90
    
    isPara = isPara(s1, s2)
    print(isRec(angle, isPara))
    

    isPara 提供了 2 个变量,您在函数内部都没有使用,您将变量更改为 b1 和 b2。如果您将变量传递给函数并想在函数中更改它的名称,请使用

    def isPara(b1, b2):
    

    此外,由于 isRec 既不使用 s1 也不使用 s2,因此您无需将这些值传递给 isRec 函数。

    此脚本的输出:

    True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 2011-02-05
      • 2013-08-20
      • 1970-01-01
      相关资源
      最近更新 更多