So this program is supposed to take a letter the user wants to replace, and store that in a dictionary. At the end, it asks the user to enter a message and it's supposed to decode it, cross-referencing the dictionary and replacing any letters within it to the newly assigned letter. I'm stuck around the decode function. I was told using a for loop and if statement with an accumulator variable should suffice, but I have no idea how to move forward.

def get_code():

    code = {} # empty dictionary

    letter = raw_input ("Enter the letter you want to substitute (to stop, enter a blank): ")
    replace = raw_input ("Enter the letter you want to replace with the letter %s: " % letter)
    print "\n"

    # collect inputs until done collecting
    while letter != "":

        code[letter] = replace

        letter = raw_input ("Enter the letter you want to substitute (to stop, enter a blank): ")
        replace = raw_input ("Enter the letter you want to replace with the letter %s: " % letter)
        print "\n"

    message = raw_input ("Now, enter the coded message: ")

    
def decode(code_dict,message):

    for letter in message:
        
        if ch in code_dict:
        
        # accumulator variable



    # seperates message by its characters
   # mes_ch = list(message)

    # if key is in the dictionary, prints value
    # if not, prints original
   # code.get(mes_ch,mes_ch)
    
def main():
    code_dict, message = get_code()
    decode(code_dict, message)

main()

This should give you an idea. There is also a problem with get_code(). You should first test what you post as much as possible.

def decode(code_dict,message):
    coded_message = []
    for ch in message:
        if ch in code_dict:
            coded_message.append(code_dict[ch])
        else:
            coded_message.append(ch)
    print "".join(coded_message)

decode({"t":"x", "b":"y"}, "the quick brown fox")

...and it is not really more complicated code to say:

def decode(code_dict,message):
    return "".join(code_dict[c] if c in code_dict else c for c in message)

print(decode({"t":"x", "b":"y"}, "the quick brown fox"))

Thank you!! and sorry, I didn't realize. I should be able to figure out the rest now

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.