[英]How to call a function with return value inside an if statement in python
[英]How to call function inside “if” statement?
我试图在给定的字符串中找到最长的回文。 我遇到了if
语句的奇怪行为。 在这里发布这两个代码,当我尝试调试时,在第一个代码中一切正常,直到 if 语句,但即使在获得True
之后,它也不会访问内部的进一步代码。
而在第二个代码中,我将回文 function 的返回值存储在 boolean var 中,然后在 if 语句中使用它。 现在它正在访问内部代码。
我想我在 python 中遗漏了一些非常基本的东西。 请有人能说出为什么会这样吗?
代码 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)
只需使用带括号的 if 语句:
if (bul) & (len(temp)>len(maxx)):
maxx=temp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.