Шифрование и дешифрование пароля поднимает ValueError

Я делаю программу, которая должна зашифровать пароль, который вы передаете. Однако, когда я запускаю его, возникает ошибка:

Password = float(input('Enter Password: '))

ValueError: не удалось преобразовать строку в число с плавающей точкой: 'Banana' (слово, которое я выбрал для этого теста)

Вот мой код:

#Macchiat0
#10 May 2016
#This program will encrypt and decrypt user passwords.

#init
encryptionlist = (('a','q'),
                  ('b','w'),
                  ('c','e'),
                  ('d','r'),
                  ('e','t'),
                  ('f','y'),
                  ('g','u'),
                  ('h','i'),
                  ('i','o'),
                  ('j','p'),
                  ('k','a'),
                  ('l','s'),
                  ('m','d'),
                  ('n','f'),
                  ('o','g'),
                  ('p','h'),
                  ('q','j'),
                  ('r','k'),
                  ('s','l'),
                  ('t','z'),
                  ('u','x'),
                  ('v','c'),
                  ('w','v'),
                  ('x','b'),
                  ('y','n'),
                  ('z','m'))

print('This program will encrypt and decrypt user passwords')

#Program Menu
ans = True

while True:
    print('1. Enter 1 to encrypt a password: ')
    print('2. Enter 2 to decrypt a password: ')
    print('3. Exit/Quit')
    ans = input('What do you want to do? ')

    if ans == "1":
        print("\n Enter 1 to encrypt a password: ")

        Password = float(input('Enter Password: '))
        print('Your new encryptid password is:', Password)
    if ans == "2":
        print("\n Enter 2 to decrypt a password: ")

        Password = float(input('Enter Password: '))
        print('Your new decrypted password is:', Password)
    elif ans == "3":
        print("\n Goodbye")
        break
    else:
        print("\n Not Valid Choice Try Again")

1 ответ

В Python 3.x input вернет строку. Вы можете прочитать об этом в PyDocs. Когда вы дали Python вход BananaСмущен. Вы не можете конвертировать Banana к float тип. Если вы хотите преобразовать строку в набор индексов для вашей программы, вы можете попробовать это (обратите внимание на 3 новые функции, которые я добавил и внедрил в ваш код):

encryptionlist = (('a','q'),
                  ('b','w'),
                  ('c','e'),
                  ('d','r'),
                  ('e','t'),
                  ('f','y'),
                  ('g','u'),
                  ('h','i'),
                  ('i','o'),
                  ('j','p'),
                  ('k','a'),
                  ('l','s'),
                  ('m','d'),
                  ('n','f'),
                  ('o','g'),
                  ('p','h'),
                  ('q','j'),
                  ('r','k'),
                  ('s','l'),
                  ('t','z'),
                  ('u','x'),
                  ('v','c'),
                  ('w','v'),
                  ('x','b'),
                  ('y','n'),
                  ('z','m'))

print('This program will encrypt and decrypt user passwords')

def letter_index(letter):
    return ord(letter) - 97

def encrypt(text):
    lowered_text = text.lower()
    encrypted_text = [letter_index(x) for x in lowered_text]
    encrypted_text = "".join([encryptionlist[x][1] for x in encrypted_text])
    return encrypted_text

def decrypt(text):
    lowered_text = text.lower()
    # the decryption process will yield worst case speed of O(n)
    # if you were to loop through the whole thing.
    # A faster way to sort it by the value e.g.
    sorted_encryptionlist = sorted(encryptionlist, key=lambda x: x[1])
    decrypted_text = [letter_index(x) for x in lowered_text]
    decrypted_text = "".join([sorted_encryptionlist[x][0] for x in decrypted_text])
    return decrypted_text


#Program Menu
ans = True

while True:
    # Get user input
    print('1. Enter 1 to encrypt a password: ')
    print('2. Enter 2 to decrypt a password: ')
    print('3. Exit/Quit')
    ans = input('What do you want to do? ')

    if ans == "1":
        print("\nEnter 1 to encrypt a password: ")

        Password = input('Enter Password: ')

        print('Your new encryptid password is:', encrypt(Password))
    if ans == "2":
        print("\nEnter 2 to decrypt a password: ")

        Password = input('Enter Password: ')

        print('Your new decrypted password is:', decrypt(Password))
    elif ans == "3":
        print("\nGoodbye")
        break
    else:
        print("\nNot Valid Choice Try Again")

Конечно, это слабое шифрование, если вы хотите лучшее шифрование (то, что используют профессионалы), взгляните на pycrypto.

Другие вопросы по тегам