Best idea is to denote the code inline with your text as something that’s text. You do it in ReST by adding a @::@ on a line by itself and then following it by an indention. Markdown’s just an empty line followed by indented text. Either work well for this case. It’s rare you want to show a full module at one whack, so the smaller blocks work well like this.
For the final source source, I’d create a @code/@ directory and then possibly any number of @chapterN/@ directories inside that to contain the completed code for each chapter.
For my book I’m creating the example project as I go along. Once I get to the end of the book I’ll have the entire project. At that point I’m going to throw it out (or, more accurately, create a new clean directory) and walk through all of the examples in a new Git repository. Each step will be a commit, with chapters tagged at the end. This will make it easy for me to export a full tarball with all of the code from each chapter plus provide people with a Git repo that has everything in it.