2017-05-29 129 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

相關問題