The sharps and flats are needed to create the different intervals between the notes. For example, the interval between C and D is a whole tone, while the interval between C# and D is a semitone. The semitone is a smaller interval than a whole tone, and it creates a different sound.
The black keys are also used to create chords. A chord is a group of three or more notes that are played together. The different combinations of black and white keys can create a variety of different chords.
The black keys add complexity and richness to the sound of a piano. They make it possible to play a wide variety of music, from classical to jazz to popular.