''' Purpose: produce and print the reverse of a user-supplied word (using accummulation) ''' # Please ask questions if this doesn't make sense and feel free to tell me to scroll through the code if # you missed something or ask a TA - I know there's a lot of notes! # PLEASE ASK QUESTIONS IF ACCUMULATORS DONT MAKE SENSE QUITE YET ### get word reply = input( "Enter word: " ) word = reply.strip() # Just as a reminder, .strip() takes off all leading and trailing whitespace from a string :) ### get a copy of the word through accumulation # Accumulation is an important concept in 1112! We want to build up an answer. # We want to initialize an accumulator (remember this word!) reverse = "" # ACCUMULATOR MUST START OFF AS EMPTY STRING FOR STRING ACCUMULATIONS # Initialize reverse to an empty string! # Why do we initialize it as an empty string? Because we want to add to it to build up an answer! # We want to add more characters to this empty string until we get our final string answer! # WRITE THIS DOWN: ACCUMULATOR IS INITIALIZED OUTSIDE THE FOR LOOP BEFORE THE FOR LOOP!! # As we go through the loop, we keep adding a new character in our original string to reverse. for ch in word : # reverse = "" # If we have the accumulator initialized here, we messed it all up because it'll be set as # an empty string each time so it never "builds up" - it resets itself # By setting it outside the for loop, we can use it before and after the loop while # the loop just modifies the accumulator (reverse in this case) print( "ch =" , ch ) # reverse = reverse + ch #(wrong!) reverse = ch + reverse # What we're doing now is we're taking each character in the original sequence # and adding it to the front so apple becomes elppa because it'll add the a then the p # in front of that a then the p after that and so on so that reverses the string :) print( reverse ) # Recall that reverse = something + reverse will add that new thing we wanna add and the last stored # value of reverse. ### print reverse print( reverse ) # PRINTS FINAL REVERSE STRING # Again, the purpose of accumulators is to build up something. # For building up a string, we initialize it using an empty string "" and then keep adding to it # by saying accumulator = accumulator + (whateverIwannaadd) through string concatenation # That way it keeps getting the previous value of accumulator and adding the new string(s) we wanna add to it # as we go through the for loop.