如何在 "if "语句中调用函数?

问题描述 投票:-3回答:1

我试图在一个给定的字符串中找到最长的词组。我遇到了一个奇怪的行为 if 在这里把两段代码都贴出来,在第一段代码中,当我试着调试时,直到if语句之前一切都很正常,但即使在得到了 True而在第二段代码中,我将palindrome函数的返回值存储在boolean var中,然后在if语句中使用,现在它访问的是内部代码。

而在第二段代码中,我将palindrome函数的返回值存储在boolean var中,然后在if语句中使用,现在它可以访问内部代码。

我想我在python中缺少了一些非常基本的东西。谁能告诉我为什么会出现这种情况?

代码1: 语句1

def palindrom(temp):
    if(temp==temp[::-1]):
        return True
    else:
        return False

word=input("enter the string to check  ")
maxx=""                                    #to store the longest palindrome till now
l=len(word)
for i in range(0,l):
    # if(len(maxx)>l-i):                   ## to check if remaining string is smaller than maxx
    #     print(maxx)
    #     break
    temp=word[i]                           ## testing by adding one letter at a time
    for j in range(i+1,l):
        temp=temp+word[j]
        if(temp is palindrom(temp)  and  len(temp)>len(maxx) ):
            maxx=temp                      ##updating the maxx
print(maxx)

代码2:

def palindrom(temp):
    if(temp==temp[::-1]):
        return True
    else:
        return False

word=input("enter the string to check  ")
maxx=""
l=len(word)
for i in range(0,l):
    # if(len(maxx)>l-i):  ## to check if remaining string is smaller than maxx
    #     print(maxx)
    #     break
    temp=word[i]
    for j in range(i+1,l):
        temp=temp+word[j]
        bul=palindrom(temp)  ##storting the return value of palindrome() in a boolean.
        if(bul and  len(temp)>len(maxx)):
            maxx=temp
print(maxx)
python python-3.x if-statement
1个回答
-2
投票

只要使用if语句和括号。

if (bul) & (len(temp)>len(maxx)):
    maxx=temp
© www.soinside.com 2019 - 2024. All rights reserved.