I have created many puns, including some dozens about maths, and attempt to consolidate my methods for other's learning.
Creating a pun consists in finding a connection between words and meanings which can be exploited for humour, and arranging those words and constructing a context so as to exploit that connection.
That first part is aided by knowing many words and thinking frequently about words. The kinds of connections to look for include words with multiple radically different meanings (e.g. "range" as either a stove or the output of a mathematical function). Also effective are words with components that sounds like unrelated words (e.g. "corollary" contains "Corolla"). Ideally, you find a way to phonetically break down a word into unrelated words (e.g. "del phi" like "Delphi"). Sometimes that breakdown will be one piece, i.e. the word has a homophone.
As far as I'm aware, the most direct way to advance at this is practice. Frequently force yourself to consider words you encounter to the repertoire of similar words you know, and you will find such connections eventually.
There are some ways to study to find such connections more effectively. Particularly effective for me is learning large amounts of (especially abstract) mathematics. Mathematicians tend to repurpose generic words for seemingly unrelated maths concepts (e.g. "ring", "field", "group", "blade", "basis", "open", etc). If you want to study to make puns without caring about a particular subject, you might read a dictionary, looking for words with many disparate definitions or words with homophones. (Arbitrarily reading the dictionary brings other benefits, but isn't necessarily worth it.)
You can also repeat and reframe puns. Any particular pun will be opportune on multiple occasions, so if you think of it once, you may remember it from then and retell it without the tedious search process. There are also occasions in which a particular word is strongly relevant, but the pun you remember is poorly phrased (whether overall or just for the situation) — you might recall, in that case, just the connection, but construct the phrasing anew.
As for the arrangement step, there are many ways. Look thru others' puns for examples. The riddle-joke is an easy and effective format. I expect arranging the jokes is quicker to learn and less practice-dependent than finding connections.