0

I have a homework question for replacing user inputs with other words in a dictionary. When I wrote a for loop, I can see that the first iteration replaces the key word correctly, but the second iteration replaces the next keyword in the dictionary. The problem is the first iteration doesn't get saved or gets overwritten. I'm not sure what is causing this and what could change with my code?

def main():
    #Get a phrase from the user
    print('')
    phrase = input('Enter a phrase: ')
    checkPhase(phrase)

def checkPhase(phrase):
    #Define the simple thesaurus    
    thesaurus = {
        'Happy': 'Glad',
        'sad' : 'bleak'
    }

    for key in thesaurus:
        old_word = key
        new_word = thesaurus[key]
        print(old_word) #used to help troubleshoot
        print(new_word) #used to help troubleshoot 
        new_phrase = phrase.replace(old_word,new_word)
        print(new_phrase) #used to show phrase after each iteration for troubleshooting

    print(new_phrase)

main()
Vince
  • 5
  • 6

1 Answers1

1

The problem is that the result is constantly overwritten within the loop. Instead initialize the result before the loop:

def checkPhase(phrase):
    #Define the simple thesaurus    
    thesaurus = {
        'Happy': 'Glad',
        'sad' : 'bleak'
    }

    new_phrase = phrase # <-- init
    for key in thesaurus:
        old_word = key
        new_word = thesaurus[key]
        print(old_word) #used to help troubleshoot
        print(new_word) #used to help troubleshoot 
        new_phrase = new_phrase.replace(old_word,new_word) # <-- modify
        print(new_phrase) #used to show phrase after each iteration for troubleshooting

    print(new_phrase)
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50