2015-09-19 63 views
-1

該腳本需要一個句子並對其進行編碼。代碼採用給定單詞中的每個字母,並按照單詞的長度在字母表中將其顛倒。所以「貓」變成「fwd」,「小」變成「xrfqq」,「小貓」變成「xrfgg fwd」。字母變更代碼

我想看看是否有什麼我應該做的不同,或者如果你們有一些改進建議。

#Letter altering code 

alphabet = ["a","b","c","d","e","f","g","h","i","j", 
     "k","l","m","n","o","p","q","r","s","t", 
     "u","v","w","x","y","z"] 

textIn= "" 

while textIn.lower != 'q': 
    textIn = input("Type a sentence to be translated ('q' to quit).\n"\ 
       ).lower() 
    textOut = "" 

if textIn == 'q': 
    break 
else: 
    for word in textIn.split(): 
     newWord = "" 
     for char in word: 
      if char in alphabet: 
       pos = alphabet.index(char) 
       newPos = (pos + len(word))%26 
       newChar = alphabet[newPos] 
       newWord += newChar 

      else: 
       newWord += char 

     textOut += newWord + " " 

print(textOut) 
+6

我想你想要codereview.stackexchange.com/ – pandubear

+0

你的具體問題是什麼?用肉眼,我可以看到你在'while textIn.lower!='q''中缺少括號。 – cdonts

回答

0

這很不錯。

alphabetstring.ascii_lowercase

textIn.lowertextIn.lower()

break應僅在一個循環中使用。你想pass,這意味着'無所事事'。

將新字符添加到新單詞的循環很清楚。我喜歡。然而,還有其他一些比較細緻的方法可以做到,它們更加pythonic並且仍然可以清楚。

+0

我不知道[string.ascii_lower]和[pass]。感謝您引起他們的注意 –