When music is said to be in a particular key, it means that the melody is based upon notes of the major scale (or minor scale) with the same name e.g., in the key of C, C major scale notes (i.e., C, D, E, F, G, A and B) will occur more frequently than notes that do not belong to the C scale (i.e., sharpened and flattened notes).
In the key of G, G scale notes will be most common (i.e., the notes G, A, B, C, D, E and F# will occur frequently). You will notice here that F# occurs rather than F natural. However, rather than add a sharp to every F note, an easier method is used whereby a sharp sign is placed on the F line (the top one) of the staff at the beginning of each line. This is referred to as the key signature: thus the key signature of G major is F#.
Shown here are the key signatures for all major scales so far discussed.
It can be seen, then, that each key signature is a shorthand representation of the scale, showing only the sharps or flats which occur in that scale. Where an additional sharp or flat occurs, it is not included as part of the key signature, but is written in the music, e.g., in the key of G, if a D# note occurs, the sharp sign will be written immediately before the D note, not at the beginning of the line as part of the key signature.