A pun, or paronomasia, is a form of word play that deliberately exploits ambiguity and/or duplicity of meaning of similar-sounding words for humorous and/or rhetorical effect. The use of a word in different senses or the use of words similar in sound to achieve a specific effect, as humor or a dual meaning. There is a most enabling article in Wikipedia on punning.
It is critical that word usage be deliberate in order for the act of punning to occur; accidental substitution of similar sounding but dissimilar meaning words for each other is strictly defined as malapropism.
It is common to see puns referred to as "the lowest form of humour", this however may be more of a reflection upon the referent than the act of puning. In modern western culture punning has been used by many brilliant writers such as Alexander Pope, James Joyce, Vladimir Nabokov, William Shakespeare, John Donne, and Lewis Carroll.
Punning was an important component of the ancient Ægyptian culture, literary and otherwise, wherein multiple meanings were incorporated usually in order to try and convey some meanings which are difficult to get to directly through words. Of course, since ancient Ægyptian language was normally written in hieroglyphic, they were able to access the visual type of punning easily as well as meaning and homophonic punning (Like both ancient and modern Chinese culture, due to their use of ideograms in writing), basically to play on meanings of different shapes correlated to the sounds of the actual hieroglyphs, or simply their use in the case of determinatives. The more subtle utilization of puns was more of an additive type, rather than exchange. For instance in the better translations of the Love Poetry of ancient Ægypt, one sees that the word usage, in addition to the high number of parenthetical undermeanings, relies on punning to add levels to the multiple entendres in the poems.
There are many varietals of puns such as: homophonic, homographic, heteronymic, homonymic, polysemic, metonymic, recursive, metaphorical, and/or compound. Of course some of the best puns work on several levels and fit into more than one category. And furthur, though new venues are always possible and often preferred, there are some common arenas in which punning is often on the starting lineup, such as in what are called transpositional puns, multi-lingual puns, "shaggy-dog stories", "daffynitions", "Knock-Knock" jokes, "Spoonerisms" (though again here, intentionality is key), "Tom Swifties", and of course the ubiquitous "Feghoot".
You can tune a file system, but you can't tune a fish. ('tuna fish' - from a Unix manual)
We egged on the runners, but the yolk was on us.
I've a library in my trousers. Now there's a turn-up for the books!