2017-05-29 172 views
2

使用Spyder Python 3.6此代码不会执行,表示ispal方法未定义。但是,当我运行它并首先放入一个整数(比如我的字符串输入= 0)时,它会在运行之后识别该方法。似乎我必须先通过一个分支,而不是首先调用该方法。感谢批评。Python代码不会在第一次运行时执行

s = input('enter a string: ') 
s1 = s 
s1 = s1.lower() 
s1 = s1.replace(',', '') 
s1 = s1.replace(' ', '') 

if s1.isalpha(): 
    if ispal(s1) == True: 
     print(s,' is a palindrome') 
    else: 
     print(s,' is not a palindrome') 
else: 
    print('you entered illegal chars') 


def ispal(s1): 
    if len(s1) <= 1: 
     return True 
    else: 
     #if the first and last char are the same 
     #and if all 
     return s1[0] == s1[-1] and ispal(s1[1:]) 
+4

您在调用它之后定义了该功能 – TGKL

+0

感谢您的帮助! – femmebot

回答

3

首先,如TGKL指出它的定义之前,你打电话ispal。因此调用之前定义,即:

def ispal(s1): 
    if len(s1) <= 1: 
     return True 
    else: 
     #if the first and last char are the same 
     #and if all 
     return s1[0] == s1[-1] and ispal(s1[1:]) 

if s1.isalpha(): 
    if ispal(s1) == True: 
     print(s,' is a palindrome') 
    else: 
     print(s,' is not a palindrome') 
else: 
    print('you entered illegal chars') 

其次你的回文递归函数是正确的,当你调用ispal里面本身除了。而不是ispal(s1[1:])你应该做ispal(s1[1:-1])这将删除刚刚测试的第一个和最后一个字符。

+0

这是issss @Carlos阿方索,你真的得到这个;),+1,喜欢它 –

+0

感谢您的提示,得到它的工作:-) – femmebot

1

你必须首先定义你的方法,然后调用它:

s = raw_input('enter a string: ') #use raw_input so the text it takes will give to you directly a string without "" 
s1 = s 
s1 = s1.lower() 
s1 = s1.replace(',', '') 
s1 = s1.replace(' ', '') 

def ispal(s1): 
    if len(s1) <= 1: 
     return True 
    else: 
     #if the first and last char are the same 
     #and if all 
     return s1[0] == s1[-1] and ispal(s1[2:]) # here you put ispal(s1[1:]) it doesn't work properly :/ 

if s1.isalpha(): 
    if ispal(s1) == True: 
     print(s,' is a palindrome') 
    else: 
     print(s,' is not a palindrome') 
else: 
    print('you entered illegal chars') 
+0

一个从前面和一个从后面;) – pepr

+0

Exaaaaactly我的朋友@pepr,你真的得到了这个;) –

+0

我必须仔细看看这个。我实际上得到了正确的结果 - 当它跑了。 – femmebot