Interesting question. The obvious answer would be, ‘because they are happy’. Cats do indeed purr to express the emotion of happiness, but interestingly research shows that purring may have other functions.
There isn’t a definitive answer to how purring is produced, as there isn’t a specific organ allocated to this function: it is believed that the vibration is produced by the larynx.
Cats do purr when petted by humans, but not only. They are known to purr when grooming each other; when nursing their kittens; kittens purr when they feed! It seems that cats use purring as a mean of communicating their feelings with each other and the young.
Research shows that purring may even have healing properties according to this Scientific American article