[英]How to call function inside “if” statement?
I am trying to find the longest palindrome in a given string.我试图在给定的字符串中找到最长的回文。 I came across a strange behavior of if
statement.我遇到了if
语句的奇怪行为。 posting both the codes here, in 1st code when I tried debugging everything is working fine till if statement, but even after getting True
, it is not accessing the further code inside.在这里发布这两个代码,当我尝试调试时,在第一个代码中一切正常,直到 if 语句,但即使在获得True
之后,它也不会访问内部的进一步代码。
Whereas in the second code I stored the return value of palindrome function in the boolean var and then used it in if statement.而在第二个代码中,我将回文 function 的返回值存储在 boolean var 中,然后在 if 语句中使用它。 now it is accessing the inside code.现在它正在访问内部代码。
I guess I am missing something very fundamental in python.我想我在 python 中遗漏了一些非常基本的东西。 Please can someone tell why is this happening?请有人能说出为什么会这样吗?
Code 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)
Code 2:代码 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)
Just use if statement with brackets:只需使用带括号的 if 语句:
if (bul) & (len(temp)>len(maxx)):
maxx=temp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.