2011-03-29 131 views
0

嗨即時嘗試創建使用Python 3凱撒密碼,問題是在文本,第5章問題7,我有這個目前爲止,但我不斷收到此錯誤信息,當我嘗試運行該程序,無法找出原因。Python 3凱撒密碼,請幫忙

程序:

def main(): 
    print("This program executes a Caesar cipher for a string") 

    word = input("Please enter word: ") 

    key = input("Please enter the number of positions in the alphabet you wish to apply: ") 

    message="" 
    for ch in word: 
     word= chr(ord(ch)+key) 
     newWord =(message + word) 
    print (newWord) 

main() 

錯誤:

Traceback (most recent call last): 
    File "/Users/krissinger/Documents/programing /my graphics/delete.py", line 14, in <module> 
    main() 
    File "/Users/krissinger/Documents/programing /my graphics/delete.py", line 10, in main 
    word= chr(ord(ch)+key) 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

回答

0
word= chr(ord(ch)+key) 

ORD(CH)給出了該字符的整數值。使用字符串添加它會導致TypeError,因爲+運算符對整數和字符串的使用方式不同。如果你希望密鑰是一個整數,你必須這樣做:

key = int(input("....") 

然後,你可以將它們加在一起。

+0

當我改變程序來讀取這樣的: DEF的main(): 打印(「該程序執行愷撒密碼的字符串」) 字=輸入(「請輸入單詞:」) 鍵= INT(輸入( 「請輸入你想申請在字母表的位置數: 」))爲CH字 消息=「」 : 字= CHR(ORD(CH)+鍵) newWord =(message + word) print(newWord) main() 生成的單詞是「u」? 我改變了錯誤的部分? – 2011-03-30 00:04:07

+0

@kris你需要把newWord = newWord + word。你的當前循環只會使newWord成爲最後一個字符。您需要將newWord初始化爲空字符串而不是消息。 – TheDude 2011-03-30 02:13:57