If you've played the piano for some time now or are just beginning with piano lessons, by now you know that the key signature is the sharps or flats, or in some cases the absence of sharps or flats, that appear immediately after the clef sign at the beginning of every line of music. Without a key signature, accidentals would have to be placed throughout the music in front of particular notes each and every time they occur. It is easier on the eye and mind in the long run, believe it or not, to indicate at the beginning of the line which notes will be affected by sharps or flats and then to remember to alter those notes as the song is played.
A key signature is just a convenient way of noting the sharps and flats that occur in a particular scale, specifically the one on which the melody of the song is based. There is no rule that says a melody has to stay within the boundaries set by one scale. If a melody strays from those scale tones, accidentals are used to show the variation. Since it is possible to write a song without using a key signature, and only using accidentals, it stands to reason that even in a song which has a key signature, a melody line could wander into a new key by the use of accidentals which would not affect the original key signature at all.
Applying these ideas to a song, let's say that a song basically begins and stays in the key of Ab major from the beginning to about measure 16. Then you you come upon a G7 chord, which is a very important chord being the dominant seventh in the key of C major. It normally does not occur in the key of Ab major. Now we are firmly planted in the key of C major and we can stay there until measure 31 and then in the following measure our ears get ready to hear a key change back to Ab major.
In a song, there can be a lot of shifting of tonal center as one key then another becomes king of the mountain for a few counts. When you look at sheet music, you will notice that all this key changing is done with accidentals and that the key signature is changed at the beginning of each line of the song thereafter. For more exciting, professional piano playing, find songs that modulate and change keys throughout the song. This will surely add spice to your piano playing!
Warmest Regards,
LadyD