As cpuobsessed said, if you want to write a window manager, it would be a good idea to learn C/C++, although you can write one in any Turing complete language (even Haskell). To answer the question posed in the title of this thread, the best way to learn to code is simply to write code. Get yourself a good online resource, PDF, or book about whatever language you want to learn and follow along in it until you feel comfortable enough to mess around on your own. Then, mess around on your own. The more time you spend programming the better you will get. As for good, well commented window managers, I've got a bit of a bias toward dwm http://dwm.suckless.org/
because it's in C, only a wee bit over 2000 lines, and is a perfect example of what a small yet well documented projects should look like.
Good luck and happy hacking.