Возникли проблемы при сравнении ключей со значениями, заданными пользовательским вводом в Python - PullRequest
0 голосов
/ 13 января 2020

Я пытаюсь создать двусторонний переводчик азбуки Морзе как проект для начинающих в Python, используя словарь для сравнения каждого символа азбуки Морзе с его последовательностью Морзе. Проблема, в частности, связана с опцией decryption , так как мой текущий код дешифрования построен так, чтобы принимать каждый отдельный символ каждой последовательности, пока он не прочитает пробел, и в этот момент он должен напечатать букву, соответствующую последовательность, затем очистите трекер последовательности для всего после пробела. Во всех случаях расшифровка вместо этого ничего не выводит, пропуская прямо от принятия ввода к предположению, что расшифровка закончилась и возвращаясь к меню, фактически не выводя ни одну из букв, последовательности которых были в пользовательском вводе.

morse_code_dict = {"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":"--..",
                   "1":".----", "2":"..---", "3":"...--", "4":"....-", "5":".....", "6":"-....", 
                   "7":"--...", "8":"---..", "9":"----.", "0":"-----"}





def encrypt(morse_code_dict):

    morse_code_current = ""

    morse_code_current = input("Please enter all of the letters and numbers you want to have encrypted. Enter the letters in uppercase." + '\n')

    for digit in morse_code_current:
        if digit in morse_code_dict.keys():
            print(morse_code_dict[digit])
            print(" ")

    print("Thank you! We'll now be bringing you back to the menu for further translation, or to exit.")
    choice()

    return

def decrypt(morse_code_dict):

    morse_code_current = ""
    morse_code_sequence = ""

    morse_code_current = input("Hello! Please enter each morse code sequence you want turned into a character. Separate each individual sequence with a space." + '\n')

    for digit in morse_code_current:
        if digit == "." or "-":
            morse_code_sequence += digit
        elif digit == " ":
            print(morse_code_dict.keys(morse_code_sequence))
            morse_code_sequence = ""
        else:
            print("One or more of these morse code sequences is inaccurate. Please double-check and try again.")
            decrypt(morse_code_dict)
            morse_code_sequence = ""
    print("Thank you! We'll now be bringing you back to the menu for further translation, or to exit.")
    choice()

    return

def choice():
    input_tracker = ""


    input_tracker = input("Enter your choice now." + '\n')

    if input_tracker == "E":
        encrypt(morse_code_dict)
    elif input_tracker == "D":
        decrypt(morse_code_dict)
    elif input_tracker == "Q":
        exit()
    else:
        print("Please enter a character corresponding to the options shown initially." + '\n')
        choice()

print("Welcome to the both-ways morse code translator!")
print("Please enter 'E' if you want to encrypt a series of characters.")
print("Enter 'D' if you want to decrypt a morse code series.")
print("Enter 'Q' to exit the program.")
choice()

1 Ответ

0 голосов
/ 13 января 2020

Я внес пару изменений в l oop:

 morse_code_dict = {"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":"--..",
                   "1":".----", "2":"..---", "3":"...--", "4":"....-", "5":".....", "6":"-....",
                   "7":"--...", "8":"---..", "9":"----.", "0":"-----"}





def encrypt(morse_code_dict):

    morse_code_current = ""

    morse_code_current = input("Please enter all of the letters and numbers you want to have encrypted. Enter the letters in uppercase." + '\n')

    for digit in morse_code_current:
        if digit in morse_code_dict.keys():
            print(morse_code_dict[digit])
            print(" ")

    print("Thank you! We'll now be bringing you back to the menu for further translation, or to exit.")
    choice()

    return

def decrypt(morse_code_dict):

    morse_code_current = ""
    morse_code_sequence = ""

    morse_code_current = input("Hello! Please enter each morse code sequence you want turned into a character. Separate each individual sequence with a space." + '\n')

    for digit in morse_code_current:
        if digit == "." or digit == "-":  # Need to specify the variable with each 'or' condition
            morse_code_sequence += digit
        elif digit == " ":
            for letter, code in morse_code_dict.items(): # .items() and remove argument
                # Have to loop the dictionary and search.
                if code == morse_code_sequence:
                    print(letter)
                    morse_code_sequence = ""
        else:
            print("One or more of these morse code sequences is inaccurate. Please double-check and try again.")
            decrypt(morse_code_dict)
            morse_code_sequence = ""
    print("Thank you! We'll now be bringing you back to the menu for further translation, or to exit.")
    choice()

    return

def choice():
    input_tracker = ""


    input_tracker = input("Enter your choice now." + '\n')

    if input_tracker == "E":
        encrypt(morse_code_dict)
    elif input_tracker == "D":
        decrypt(morse_code_dict)
    elif input_tracker == "Q":
        exit()
    else:
        print("Please enter a character corresponding to the options shown initially." + '\n')
        choice()

print("Welcome to the both-ways morse code translator!")
print("Please enter 'E' if you want to encrypt a series of characters.")
print("Enter 'D' if you want to decrypt a morse code series.")
print("Enter 'Q' to exit the program.")

choice()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...