为什么我的Python2.7代码在组件为true时打印“false”?

2024-10-01 07:29:07 发布

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

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

#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)

Tags: the函数falsetrueifdefit语句
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提供了两个变量,您在函数中都没有使用,而是将变量更改为b1和b2。如果将变量传递给函数并希望在函数中更改其名称,请使用

def isPara(b1, b2):

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

此脚本的输出:

True

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

相关问题 更多 >