Sharps and flats serve the same function in two different ways; they both alter the pitch of a given note by one half-step. Sharps raise the pitch of a note by one half-step and are notated with a "#" symbol. Flats lower the pitch of a note by one half-step; they are notated with a symbol that resembles a "b". These notations may be found both in the key signature of the entire piece or next to -- and altering -- an individual note.
A key signature sets rules that apply to certain notes within an entire musical composition. The key signature appears at the beginning of a piece, and indicates which notes are raised and lowered throughout the work; every time they appear in the music they are always altered accordingly by the player (unless otherwise indicated). For example, if a b-flat is in the key signature, every time a "b" appears it should be read as a b-flat.
Accidentals are the exception to a key signature, and they indicate when a note does not follow the rules set forth by the sharps and flats in the key signature. Accidentals may be marked with a flat symbol, sharp symbol or natural symbol, which returns the note to its original pitch. An accidental only applies to notes in the rest of a measure, and constitutes an exception to the rules of the key signature. For example, a c-sharp might be in the key signature, but if one specific c-sharp in a song is altered with a natural symbol it indicates that a c-natural should be played instead.
Sharps and flats always appear in the same order in a key signature, and they are governed by the concepts of the "order of sharps" and "order of flats." Sharps appear in this order: F C G D A E B. That is, if a key signature has three sharps, those sharps are F#, C# and G#, because these are the first in the sequence. A key with four sharps would have the sharps F#, C#, G# and D#. For flats, the rule is the same, but the order of the notes is reversed: B E A D G C F.