我当前的程序存在一个问题,该程序应该接受用户输入,然后通过允许您选择要移动多少来进行加密,然后保存到文件中,从而对其进行加密。出于未知原因,我的程序似乎能够保存文件,但是完全没有加密。任何帮助将不胜感激。

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

最佳答案

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))

10-06 05:19
查看更多