2015-04-01 69 views
1

我有一個問題與我當前的程序,它應該採取用戶輸入,通過允許您選擇多少你想轉移,然後保存加密它到一個文件。由於未知的原因,我的程序似乎能夠保存文件,但它完全錯過了加密。任何幫助非常感謝。腳本加密,但仍然保存明文而不是密文

text = "abcdefghijklmnopqrstuvwxyz 1234567890-=!£%^&*" 

def main(): 
    #if they want to save the file after the encrypting if statement 
    ans = input("Would you like to save to a file of read a file, press w or r").lower() 

    if ans == "w": 
     text = input("What is your text you want to enter").lower() 

     caeser(text) 
     save_file() 

    elif ans == "r": 
     text = input("What is your file name you want to enter").lower() 
     caeser(text) 

# organise loop & function 
def caeser(text): 
    shift = int(input("How much would you like to shift?: ")) 
    shifted_list = [] 
    for letter in text: 
     character_lower = letter.lower() 
     ASCII = ord(character_lower) 
     shift = shift % 26 
     shifted_letter = ASCII + shift 
     shifted_char = chr(shifted_letter) 
     shift_loop = shifted_letter - 26 
     shift_loop_char = chr(shift_loop) 
     if shifted_letter >= 97 and shifted_letter <= 122: 
      shifted_list.append(shifted_char) 
      text = ''.join(shifted_list) 
     elif shift_loop >= 97 and shift_loop <= 122: 
      shifted_list.append(shift_loop_char) 
      text = ''.join(shifted_list) 
     else: 
      shifted_list.append(character_lower) 
      text = ''.join(shifted_list) 
     encrypted = text 
    return encrypted 

# save file shouldnt return text 
def save_file(text): 
    name = input("Enter filename") 
    file = open(name, "w") 
    file.write(text) 
    file.close() 

#load file shouldnt recieve a parameter 
# error protection needs to be added 
def load_file(text): 
    name = input("Please enter a file name") 
    file = open(name, "r") 
    text = file.read() 
    file.close() 
    return text 
+0

'encrypted = text'不應該在'for'循環中 - 您將覆蓋每個字母。放下它。 – tdelaney 2015-04-01 17:12:34

回答

1

Python字符串是immutable。你需要改變這一點:

# returns encrypted text and does nothing with it 
caeser(text) 
# saves 'text' from module-level namespace, since you send nothing 
save_file() 

要這樣:

# send encrypted text returned by 'caesar(text)' to save_file 
save_file(caeser(text)) 
+0

非常感謝很多人:) – 2015-04-01 17:26:02

1
caeser(text) 
    save_file() 

返回值不分配給任何一個變量,所以你只是把這樣的結果。

text = caeser(text) 

會解決這個問題。

+1

OP沒有名爲'new_char'的變量。除了你注意到的問題之外,他的問題是'encrypted = text'在錯誤的地方(或者應該是'encrypted + = text'我沒有算出他的算法)。 – tdelaney 2015-04-01 17:14:08

+0

我知道(知道嗎?)他沒有newchar ...我只是展示瞭如何連接char +字符串。無論如何,答案的那部分是不正確的 - 他確實返回了一個字符串(我沒有注意到這個連接),所以我刪除了這部分答案。 – jcoppens 2015-04-01 17:22:52